Expressions
Writing expressions in bash is pretty straightforward. There are 2 different ways to evaluate conditions in the bash shell. The first method, using test enables you to check variables to see what they contain, and so forth. The second technique is to rely on the exit status code generated by other programs to determine what course of action to take.
test
The test command will evaluate expressions and return a true or true value depending on the parameters that are supplied to test and the mode that it is operating in. For example, to check a variable, for equality, you could do this:
The text contained in the variable name must exactly evaluate to "John" (capitalization matters!) in order to be considered true. Typically, to see if an expression isn't true, you use the ! character to negate the test. To check if "$name" isn't equal to "John", the following code will do the trick:test "$name"="John"
test "$name" != "John"
There are many other ways that test can operate (Some are listed below). For full information about test, read its man page.
test $variable
- Test to see if the variable is storing any data. If it is, the test evaluates true.test -z $variable
- Test a variable for zero length (no data). Returns true if the variable is empty.test $variable1 -eq $variable2
- Test for equality between integers. Returns true if $variable1 and $variable2 are equal.test $variable1 -ge $variable2
- Test to see if $variable1 is greater than or equal to $variable2.test $variable1 -gt $variable2
- Returns true if $variable1 is greater than $variable2.test $variable1 -le $variable2
- Returns true if $variable1 is less then or equal to $variable2.test $variable1 -ne $variable2
- Returns true if the variables are not equal.test $file1 -nt $file2
- Checks modification dates of 2 files. Returns true if $file1 is newer than $file2.test -e $file
- Checks to see if the file named in $file exists.test -d $file
- Checks to see if the named file is a directory and exists.Evaluating the results of a command
Commands exit with a status code that is equivalent to "true" if the command completed successfully, or "false" if not. You can use the exit codes as an expression. For example, you can simply input a username into the variable username to see if the user is included in the system's password file. If you're familiar with the grep command, this simple line would take care of the problem:
Thegrep "$username" /etc/passwd >/dev/null
> /dev/null
portion of the line ensures that any output from the grep command isn't displayed.