New to Bash scripting. I came across this line in the script file which I find difficult to understand
[ "$variable" ] || echo 'variable is unset or empty!' >&2
What is ||
used for?
It is the logical OR operator. echo is executed if, and only if, test condition returns a non-zero exit status.
See here for more details: http://bash.cyberciti.biz/guide/Logical_OR
粗略翻译成英文,它的意思是“如果失败,请执行此操作”。
基本上,如果第一个命令成功执行,第二个命令将永远不会执行。
1 == 1 || echo 'math is broke'
The form of the expression something || something else
something || something else
or something && something else
is called a compound command . There can be 2 or more commands and you can use { ...; ...; }
{ ...; ...; }
{ ...; ...; }
to collect multiple commands together after each ||
or &&
. For example, to check that the user provides 2 valid filenames on the command line for a script:
[ -f "$1" ] && [ -f "$2" ] || {
printf "error: invalid input. Usage: %s <file1> <file2>\n" "${0//\//}"
exit 1
}
Which simply requires that the test of the first argument [ -f "$1" ]
( &&
and) the test of the second argument [ -f "$2" ]
are both files making each test evaluate to true
. Otherwise ( ||
or) print the error message and exit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.