Changes

Jump to navigation Jump to search
Line 29: Line 29:  
===Exit status at the CLI===
 
===Exit status at the CLI===
 
Exit status is not limited to shell script. Every time command terminated shell gets an exit code indicating success or failure of the command. Hence we can use the particular bash variable $? to get the exit status of the command. For instance:
 
Exit status is not limited to shell script. Every time command terminated shell gets an exit code indicating success or failure of the command. Hence we can use the particular bash variable $? to get the exit status of the command. For instance:
<syntaxhighlight lang="bash" >ping -q -c 4 www.cyberciti.biz >/dev/null
+
<syntaxhighlight lang="bash" >$ ping -q -c 4 www.cyberciti.biz >/dev/null
echo $?</syntaxhighlight>
+
$ echo $?</syntaxhighlight>
 
Output:
 
Output:
 
<pre>0</pre>
 
<pre>0</pre>
Line 37: Line 37:  
## will get the exit status of the last command in the pipeline ##
 
## will get the exit status of the last command in the pipeline ##
 
echo $?</syntaxhighlight>
 
echo $?</syntaxhighlight>
 +
===Execute commands based upon  the exit status===
 +
Run command2 if command1 is successful using [[Logical AND]] (<kbd>&&</kbd>) operator:
 +
<syntaxhighlight lang="bash" >command1 && command2</syntaxhighlight>
 +
For example, if wget command found in execute the [[echo command]]
 +
<syntaxhighlight lang="bash" >$ type -a wget >/dev/null && echo "wget command found. Download the Linux kernel ..."</syntaxhighlight>
 +
Similarly, bar command is executed if, and only if, foo command returns a non-zero exit status using [[Logical OR]] operator:
 +
<syntaxhighlight lang="bash" >$ foo || bar</syntaxhighlight>
 +
Therefore we can combine bash Exit command and exit codes to build quick logic as follows:
 +
<syntaxhighlight lang="bash" >$ my_command && echo "Done" || echo "Failed"
 +
$ /usr/bin/rsnapshot daily && echo "Backup successful" || echo "Backup failed. Alerting OPS team..."
 +
$ mkdir /opt/kernel && cd $_ && echo "Directory created and you are in $PWD"</syntaxhighlight>
 +
We can group commands as a unit as follows:
 +
<syntaxhighlight lang="bash" >##  Execute conditional command  using the [[ and Logical AND ##
 +
[ -f /path/to/file ] && { echo "File found. Starting ...";
 +
                          /path/to/command2;
 +
                          /path/to/command3 arg1 arg2;
 +
                        }
 +
## another example
 +
[[ "$value" != "Yes" ]] && {
 +
                              _errs=("${_errs[@]}" "<p>The I/O thread for reading the master's binary log not found ($v: $value)</p>");
 +
                              _is_error_found="true";
 +
                            }</syntaxhighlight>
    
==Shell script example==
 
==Shell script example==

Navigation menu