Open main menu

CDOT Wiki β

Changes

BASH Exit Status

1,689 bytes added, 15:39, 12 October 2008
The test Command
Will exit the script with an exit code of 2.
 
= The test Command =
 
BASH has a built-in test command (similar to <code>/bin/test</code>) which can perform basic string and integer comparisons using these operators (results are returned as an exit code):
 
{|class="mediawiki" border="1"
 
|-
!Operator
!Comparision type
!Comparison
!Example
 
|-
|<nowiki>-eq</nowiki>
|Integer
|Equal
| $x -eq 4
 
|-
|<nowiki>-ne</nowiki>
|Integer
|Not equal
| $x -ne 4
 
|-
|<nowiki>-gt</nowiki>
|Integer
|Greater than
| $x -gt 0
 
|-
|<nowiki>-lt</nowiki>
|Integer
|Less than
| $x -lt 1000
 
|-
|<nowiki>-ge</nowiki>
|Integer
|Greater than or equal to
| $x -ge $y
 
 
|-
|<nowiki>-le</nowiki>
|Integer
|Less than or equal to
|$x -le 96
 
|-
|=
|String
|Equal
|"$x" = "Y"
 
|-
|!=
|String
|Not equal
|"$x" != "NEVER"
 
|}
 
There are also a number of unary file tests, including:
 
{|class="mediawiki" border="1"
 
|-
!Operator
!Test
!Example
 
|-
|<nowiki>-e</nowiki>
|File exists
| [ -e /etc/passwd ]
 
|-
|<nowiki>-r</nowiki>
|File is readable
|[ -r /etc/hosts ]
 
|-
|<nowiki>-w</nowiki>
|File is writable
|[ -w /tmp ]
 
|-
|<nowiki>-x</nowiki>
|File is executable
|[ -x /usr/bin/ls ]
 
|-
|<nowiki>-f</nowiki>
|File is a regular file
|[ -f /dev/tty ]
 
|-
 
|<nowiki>-d</nowiki>
|File is a directory
|[ -d /dev/tty ]
 
|}
 
These tests and comparisons are used with the <code>test</code> command or the synonym, <code>[</code> command:
 
$ test 10 -gt 5
$ echo $?
0
 
$ test 10 -lt 5
$ echo $?
1
 
$ [ 10 -lt 5 ]
$ echo $?
1
 
$ [ -f /etc/passwd ]
$ echo $?
0
 
$ [ -w /etc/passwd ]
$ echo $?
1
 
Tests can be combined with -o (or) and -a (and), and negated with !
 
$ a=500
$ [ "$a" -ge 100 -a "$a" -le 1000 ]
$ echo $?
0
 
$ [ ! "a" = "b" ]
$ echo $?
0
= Exit Codes and Flow Control =