Is there a list of all the if
switches for use in Bash scripting? Sometimes I see someone using it and I wonder what the switch they're using actually does.
An example is the -z
in this one. I know how to use it, but I don't know where it was derived from.
if [ -z "$BASH_VERSION" ]; then echo -e "Error: this script requires the BASH shell!" exit 1 fi
Any references, guides, posts, answers would be appreciated.
-n string True if the length of string is non-zero. -a file True if file exists.
The -n operator is for checking if a variable has a string value or not. It is true if the variable has a string set. This is a great way to test if a bash script was given arguments or not, as a bash scripts arguments are placed into variables $1 , $2 , $3 and so on automatically.
The n command lets you step over function calls in your scripts. This command saves you time because you won't need to single-step through every line of every function. The program below has three functions defined and three function calls and is used to demonstrate the n command.
Look at the Bash man page (man bash
). The options are specified in the CONDITIONAL EXPRESSIONS
section:
CONDITIONAL EXPRESSIONS Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. Expressions are formed from the following unary or binary primaries. If any file argument to one of the pri- maries is of the form /dev/fd/n, then file descriptor n is checked. If the file argument to one of the primaries is one of /dev/stdin, /dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively, is checked. Unless otherwise specified, primaries that operate on files follow sym- bolic links and operate on the target of the link, rather than the link itself. -a file True if file exists. ... more options ...
It is also explained in the help:
$ help [ [: [ arg... ] This is a synonym for the "test" builtin, but the last argument must be a literal `]', to match the opening `['.
Yes. These are called conditional expressions and these are used by the [[
compound command and the test
and [
builtin commands ([
is simply a synonym for test
).
Read section 6.4 Bash Conditional Expressions of the Bash Reference Manual, which contains a list of all these switches and their usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With