z1-lk-bos/script
2024-12-10 21:14:56 +03:00

149 lines
3.4 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
LOG_FILE=""
ERR_FILE=""
SHOW_USERS=0
SHOW_PROCESSES=0
SHOW_HELP=0
ERROR_OCCURRED=0
# Функция отображения справки
display_help() {
echo "Usage: $0 [options]."
echo "Options:"
echo " -u, --users Display a list of users and their home directories"
echo " -p, --processes Display a list of running processes"
echo " -l, --log PATH Redirect output to a specified file"
echo " -e, --errors PATH Redirect error output to a specified file"
echo " -h, --help Show this message and terminate"
}
# Проверка доступности пути
check_path() {
local path="$1"
touch "$path" 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error: Cannot write to $path" >&2
return 1
fi
return 0
}
# Ручная обработка аргументов для раннего перенаправления
for ((i = 1; i <= $#; i++)); do
if [[ ${!i} == "-e" || ${!i} == "--errors" ]]; then
next=$((i + 1))
ERR_FILE=${!next}
break
fi
done
# Настройка вывода ошибок
if [[ -n "$ERR_FILE" ]]; then
if ! check_path "$ERR_FILE"; then
exit 1
fi
exec 2>"$ERR_FILE"
fi
# Парсинг аргументов через getopt с фиксацией ошибок
PARSED=$(getopt -o hupl:e: --long help,users,processes,log:,errors: -- "$@" 2>&1)
GETOPT_STATUS=$?
if [[ $GETOPT_STATUS -ne 0 ]]; then
ERROR_OCCURRED=1
echo "$PARSED" >&2
display_help >&2
exit 1
fi
# Преобразование параметров после обработки getopt
eval set -- "$PARSED"
# Обработка аргументов
while true; do
case "$1" in
-h|--help)
SHOW_HELP=1
shift
;;
-u|--users)
SHOW_USERS=1
shift
;;
-p|--processes)
SHOW_PROCESSES=1
shift
;;
-l|--log)
LOG_FILE="$2"
shift 2
;;
-e|--errors)
ERR_FILE="$2"
shift 2
;;
--)
shift
break
;;
*)
ERROR_OCCURRED=1
echo "Invalid option: $1" >&2
display_help >&2
exit 1
;;
esac
done
# Настройка вывода в лог-файл
if [[ -n "$LOG_FILE" ]]; then
if ! check_path "$LOG_FILE"; then
exit 1
fi
exec 1>"$LOG_FILE"
fi
# Основная логика
main() {
if [[ $SHOW_HELP -eq 1 ]]; then
display_help
exit 0
fi
# Выполнение запрошенных действий
if [[ $SHOW_USERS -eq 1 && $SHOW_PROCESSES -eq 1 ]]; then
ERROR_OCCURRED=1
echo "Error: Cannot use both -u and -p options simultaneously." >&2
display_help >&2
exit 1
fi
if [[ $SHOW_USERS -eq 1 ]]; then
echo "USER HOME"
list_users
elif [[ $SHOW_PROCESSES -eq 1 ]]; then
list_processes
else
ERROR_OCCURRED=1
echo "Error: No action specified." >&2
display_help >&2
exit 1
fi
if [[ $ERROR_OCCURRED -eq 0 ]]; then
echo "Execution completed successfully. No errors occurred." >&2
fi
}
list_users() {
awk -F: '{print $1, $6}' /etc/passwd | sort
}
list_processes() {
ps -eo pid,comm --sort=pid
}
# Вызов основной функции
main