sections in this module | City College of San Francisco - CS160B Unix/Linux Shell Scripting Module: Conditionals |
module list |
The test command is the most-often used command in control constructs in the shell. Test does just what it's name implies - it tests a condition.
The test command is discussed at length in your Shotts text, and it includes fairly exhaustive tables of test options, so we will not repeat those here. We will only highlight a few issues that cause confusion.
Abbreviated syntax
Everyone understands the syntax for the following command:
test -f "$file"
We are running the command test with the option -f and a variable that appears to hold the name of a file. The following things should be obvious to any shell programmer
However, the more common way to run the test command is using the abbreviated syntax with [ ]:
[ -f "$file" ]
Now it looks like we can relax the spacing and quoting restrictions, but this is just a test command in disguise. However, we are still running a command - it's name is just [ :
Now, in actuality, [ is a built-in shell command, so the external command [ is just a fail-safe. However, it does shed light on what is happening here:
$ [-f "$file" ]
bash: [-f: command not found
$
The [[ ]] operator
In addition to the single square brackets, bash offers a double square bracket construct to provide additional test-style operators. Unlike [ ], [[ ]] is not a synonym for a command, but similar syntax restrictions apply.
[[ ]] accepts all the standard test operators. Some of the most useful additions and modifications are below:
Examples:
[[ "$string1" < "$string2" ]] succeeds if $string1 is lexicographically less than $string2.
Note that this uses the current locale, so, on Linux, this probably
does a case-insensitive comparison. (If you don't know what the
'locale' is, this makes a good Google Group question.
[[ "$file" == *.pdf ]] succeeds if $file contains a string that ends in .pdf
[[ "$file" == *\** ]] or [[ "$file" == *"*"* ]] succeeds if $file contains a string that contains an asterisk (*)
[[ "$name" =~ [[:alpha:]]+ ]] succeeds if $name contains only alphabetic characters and is not empty.
Note that these constructs are not very useful until they are combined with if or while statements. if statements are next.
Prev | This page was made entirely with free software on Linux: Kompozer and LibreOffice |
Next |