Bash Logic 2

Doing logic with [[ and ]]

(this topic is covered in the bash manual here)

 1$> 
 2$> ls -l
 3total 4
 4-rw-rw-r-- 1 osboxes osboxes 6 Jan 21 08:39 myfile
 5$> 
 6$> [[ -f myfile ]]
 7$> echo $?
 80
 9$> [[ -f myfile5 ]]
10$> echo $?
111
12$> 
  • example 2: is this the correct lexicographical order?
1$> 
2$> [[ camera > computer ]]
3$> echo $?
41
5$> [[ server > bannana ]]
6$> echo $?
70
8$> 
  • example 3: arithmetic comparing
1$> 
2$> [[ 15  -lt  19 ]]
3$> echo $?
40
5$> [[ 15  -lt 8 ]]
6$> echo $?
71
8$> 
1$> 
2$> [[ $(( 4+5 ))  -gt 7 ]] 
3$> echo $?
40
5$> echo $(( 4+5 ))
69
7$> 

The older [ and ]

(this is covered here)

  • The original Bourne shell used a command called test.
    Bash keep supporting this because it is part of the POSIX standard that tries to make UNIX system work the same.
    (see Bourne shell builting)
  • It works the verys similar to the [ and [[ commands:
 1> 
 2$> ls -l
 3total 4
 4-rw-rw-r-- 1 osboxes osboxes 6 Jan 21 08:39 myfile
 5$> test -f myfile 
 6$> echo $?
 70
 8$> test -f file5
 9$> echo $?
101
11$> 
  • Another example:
1$> 
2$> test $(( 5 + 2 )) -gt 9
3$> echo $?
41
5$> 
6$> test $(( 5 + 2 )) -eq 7
7$> echo $?
80
9$> 
  • Both test and [ are executable commands.
    There is also a shell builtin for [.