Содержание

How to program with Bash: Logical operators and shell expansions If в Bash: от новичка до профессионала

IF THEN ELSE

if условие; 
then
 команда вернула 0;
else
 команда вернула не 0;
fi
 
if ls /etc/passwd;
then
 echo File OK;
else 
 echo No file;
fi
 
 
if условие1; then команды1; elif условие2; then команды2; else команды3; fi
 
 
 
if КОМАНД1; then КОМАНДЫ; elif КОМАНД2; then КОМАНДЫ; else КОМАНДЫ; fi
 
if КОМАНД1; then КОМАНДЫ; fi
 
if КОМАНД1; then КОМАНДЫ; fi ≡ КОМАНД1 && КОМАНДЫ

e functional syntax of these comparison operators is one or two arguments with an operator that are placed within square braces, followed by a list of program statements that are executed if the condition is true, and an optional list of program statements if the condition is false:

if [ arg1 operator arg2 ] ; then list or if [ arg1 operator arg2 ] ; then list ; else list ; fi The spaces in the comparison are required as shown. The single square braces, [ and ], are the traditional Bash symbols that are equivalent to the test command:

if test arg1 operator arg2 ; then list There is also a more recent syntax that offers a few advantages and that some sysadmins prefer. This format is a bit less compatible with different versions of Bash and other shells, such as ksh (the Korn shell). It looks like:

if arg1 operator arg2 ; then list

Способы проверки условий

УсловиеОписание
-zстрока пуста
-nстрока не пуста
=, ( == )строки равны
!=строки не равны
-eqравно
-neне равно
-lt,(<)меньше
-le,(⇐)меньше или равно
-gt,(>)больше
-ge,(>=)больше или равно
!отрицание логического выражения
-a,(&&)логическое «И»
-o,(||)логическое «ИЛИ»
-fпроверка существования файла

Команда test

Команда test проверяет типы файлов и сравнивает значение. Возвращает 0 если True, 1 если False Больше информации о test

# Сравнение переменной со строкой
test "$MY_VAR" == "/bin/zsh"
 
# Проверка, если переменная пустая
test -z "$GIT_BRANCH"
 
# Проверка на существование файла
test -f "path/to/file_or_directory"
 
# Проверка на существование папки
test ! -d "path/to/directory"
 
# If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):
test condition && echo "true" || echo "false"

Примеры

&&запустить следующую команду, если первая вернула True
||
!отрицание

Команды выполняются слева направо. true && true ||false && true && echo "ok" Можно использовать скобки true && true ||(false && true) && echo "ok"

test команда проверяет различные условия, связанные с файлами и возвращает логический аттрибут

pgrep sshd && echo "OK"Проверить, что процесс sshd запущен и вывести OK
$? возвращает код ошибки

0 - true, 1 - ошибка

Примеры

pgrep sshd && echo "OK"Проверить, что процесс sshd запущен и вывести OK