Bash Expressions: Difference between revisions
Jump to navigation
Jump to search
(→&&) |
|||
Line 77: | Line 77: | ||
====&&==== | ====&&==== | ||
<syntaxhighlight lang='bash'> | |||
[[ -n ${var} && -f ${var} ]] && echo "${var} is a file" | |||
</syntaxhighlight> | |||
====||==== | ====||==== | ||
[[ -b ${var} || -c ${var} ]] && echo "${var} is a device" | [[ -b ${var} || -c ${var} ]] && echo "${var} is a device" |
Revision as of 08:58, 27 March 2020
Internal
Conditional Expressions
Difference between -a and &&
If want to combine the results of multiple command executions in an if condition, use &&, not -a.
Example:
if grep "something" /file1.txt && grep "something" /file2.txt' then # "something" exists in both files ... fi
-a should be used in test expressions:
if [ -f /file.txt -a -x /file.txt ]; then ... fi
[[...]] Extended Test Command
[ and "test" are equivalent: [...] is part of the shell built-in command test. [[ is a keyword rather than a program, and it is called the extended test command. [ and [[ have much in common and share many expression operators like "-f", "-s", "-n", and "-z".
Notable differences:
- [[ allows =~ and regular expression matching.
- Variables do not have to be quoted inside [[...]] because [[ handles empty strings or strings with spaces more intuitively.
- < and > can be used for string comparison.
This is a systematic comparison of the [[...]]'s feature compared with [...]:
String Comparison
>
[[ a > b ]] || echo "a does not come after b"
<
[[ az < za ]] && echo "az comes before za"
= (or ==)
a = a && echo "a equals a"
!=
a != b && echo "a is not equal to b"
Integer Comparison
-gt
5 -gt 10 || echo "5 is not bigger than 10"
-lt
8 -lt 9 && echo "8 is less than 9"
-ge
3 -ge 3 && echo "3 is greater than or equal to 3"
-le
3 -le 8 && echo "3 is less than or equal to 8"
-eq
5 -eq 05 && echo "5 equals 05"
-ne
6 -ne 20 && echo "6 is not equal to 20"
Conditional Evaluation
&&
[[ -n ${var} && -f ${var} ]] && echo "${var} is a file"
||
[[ -b ${var} || -c ${var} ]] && echo "${var} is a device"
Combining Conditional Evaluation with Command Result
A test expression can be combined with a regular command result by using [[...]] around the test expression and combining the resulted expression with the command, as follows:
if [[ -f ./a ]] && ! diff -q ./a ./b >/dev/null; then
# ...
fi
Expression Grouping
[[ ${var} = img* && (${var} = *.png || ${var} = *.jpg) ]] && echo "${var} starts with img and ends with .jpg or .png"
Pattern Matching
[[ ${name} = a* ]] || echo "name does not start with an 'a': ${name}"
Regular Expression Matching
$(date) =~ ^Fri\ ...\ 13 && echo "It's Friday the 13th!"
((...))
The double parentheses construct.