Conditional Expressions in BASH
- Bash uses the command test to do logical tests.
- test expression
- [ expression ]
- In either case, it sets the exit code
- But this is reverse from C.
- 0 indicates true
- not 0 indicates false
- It is important to have a space before and after the [ and ]
- Logical
- Empty expression is false.
- ! is not.
- -a is logical and, -o is logical or
- String Operations
- -n string : true if the length of a string is not 0
- But you can just give the string as well for this.
- -z string : true if the length of a string is 0
- = works for strings,
- as does !=
- Integers
- Welcome to fortran: -eq, -ge, -gt, -le, -lt, -ne
- But the real strength is with files
- file1 -ef file2 : same device and inode numbers.
- file1 -nt file2 : file1 is newer than file 2
- file1 -ot file2 : file1 is older than file 2
- File Types
- -b file : file exists and is block special
- -c file : file exists and is character special
- -d file : file exists and is a directory
- -e file : file exists
- -f file : file exists and is a regular file
- -h file : file exists and is a symbolic link
- -p file : file exists and is a pipe
- -S file : file exists and is a socket
- File info
- -s file : file exists and has a size greater than 0
- -r file : file exists and program can read
- -w file : file exists and program can write
- -x file : file exists and program can execute
- There are others.