Введите man bash
и прочтите документацию.
Что вы найдете там:
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
The if list is executed. If its exit status is zero, the
then list is executed. Otherwise, each elif list is executed
in turn, and if its exit status is zero, the corresponding
then list is executed and the command completes. Otherwise,
the else list is executed, if present. The exit status is
the exit status of the last command executed, or zero if no
condition tested true.
Это означает, что после , если
может быть любая команда, и bash заботится только о возвращаемом значении этой команды. Выше вы использовали две разные команды: [
и [[
.
test expr
[ expr ]
Return a status of 0 (true) or 1 (false) depending on the
evaluation of the conditional expression expr. Each operator
and operand must be a separate argument. Expressions are
composed of the primaries described above under CONDITIONAL
EXPRESSIONS. test does not accept any options, nor does it
accept and ignore an argument of -- as signifying the end of
options. [...]
Это классический тест, доступный во многих оболочках.
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression expression. Expressions are composed
of the primaries described below under CONDITIONAL EXPRES‐
SIONS. Word splitting and pathname expansion are not per‐
formed on the words between the [[ and ]]; tilde expansion,
parameter and variable expansion, arithmetic expansion, com‐
mand substitution, process substitution, and quote removal
are performed. Conditional operators such as -f must be
unquoted to be recognized as primaries.
When used with [[, the < and > operators sort lexicographi‐
cally using the current locale.
When the == and != operators are used, the string to the
right of the operator is considered a pattern and matched
according to the rules described below under Pattern Match‐
ing, as if the extglob shell option were enabled. The =
operator is equivalent to ==. If the shell option nocase‐
match is enabled, the match is performed without regard to
the case of alphabetic characters. The return value is 0 if
the string matches (==) or does not match (!=) the pattern,
and 1 otherwise. Any part of the pattern may be quoted to
force the quoted portion to be matched as a string.
Это расширение в bash с немного другим значением. В частности, ==
определяется по-другому. Первый выполняет буквальное сравнение, а второй - сопоставление с подстановочными знаками.
Нет ничего плохого в том, чтобы позволить сценарию изменить свой рабочий каталог, если его нужно запустить с определенным рабочим каталогом (из-за того, что он использует относительные пути или что-то еще ).
Единственное, что можно сделать, это выйти с не -нулевым статусом выхода, если cd
не удалось:
cd /root/demoproject || exit 1
Вы также можете изменить каталог в скрипте в зависимости от значения переменной окружения:
cd "${MY_WORK_DIR:-/root/demoproject}" || exit 1
Это изменит рабочий каталог на каталог, указанный в MY_WORK_DIR
, но по умолчанию будет /root/demoproject
, если эта переменная пуста или не установлена.