1. Approach
This docu shows some tips and tricks for shell and cmd programming
Why yet another docu as all existings?
2. History and available shell script languages
bash, POSIX
4. Bash extended conditional expressions
Note: This chapter was completely generated by chatGPT.
Bash provides extended conditional expressions using [[ … ]].
They are more powerful and safer in several situations than the
traditional [ … ] (the test command).
4.1. 1. String comparisons
[[ "$X" == "abc" ]] # Equal
[[ "$X" != "abc" ]] # Not equal
[[ -z "$X" ]] # Empty string
[[ -n "$X" ]] # Non-empty string
4.2. 2. Pattern matching
[[ "$FILE" == *.zip ]] # Ends with .zip
[[ "$FILE" == GET-* ]] # Starts with GET-
The right-hand pattern is not quoted, so * acts as a wildcard.
4.3. 3. Regular expressions
[[ "$X" =~ ^[0-9]+$ ]] # Contains only digits
4.4. 4. Logical combinations
[[ "$X" == "abc" && "$Y" == "def" ]]
[[ "$X" == "abc" || "$Y" == "def" ]]
[[ ! "$X" == "abc" ]]
No need for -a or -o, which are problematic in traditional test.
4.5. 5. File tests
These are also available in traditional test:
[[ -f "$FILE" ]] # Exists and is a regular file
[[ -d "$DIR" ]] # Exists and is a directory
[[ -r "$FILE" ]] # Readable
[[ -x "$FILE" ]] # Executable
[[ -s "$FILE" ]] # Exists and has nonzero size
4.6. Recommendation
For Bash scripts, use:
-
[[ … ]]for conditions. -
=or==for string equality (both work). -
&&and||for logical combinations.
Note that [[ … ]] is a Bash extension and is not part of POSIX shell syntax.
For scripts intended to run with /bin/sh, use [ … ] instead.