<?xml version='1.0'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:atom="http://www.w3.org/2005/Atom" >
<channel>
	<title><![CDATA[BOL: Exit Bash Script When Any Command Fails]]></title>
	<link>https://bioinformaticsonline.com/snippets/view/41352/exit-bash-script-when-any-command-fails?</link>
	<atom:link href="https://bioinformaticsonline.com/snippets/view/41352/exit-bash-script-when-any-command-fails?" rel="self" type="application/rss+xml" />
	<description><![CDATA[]]></description>
	
	<item>
	<guid isPermaLink="true">https://bioinformaticsonline.com/snippets/view/41352/exit-bash-script-when-any-command-fails</guid>
	<pubDate>Sat, 07 Mar 2020 01:10:17 -0600</pubDate>
	<link>https://bioinformaticsonline.com/snippets/view/41352/exit-bash-script-when-any-command-fails</link>
	<title><![CDATA[Exit Bash Script When Any Command Fails]]></title>
	<description><![CDATA[<code>This can actually be done with a single line using the set builtin command with the -e option.

#1------------------------------------------------------------------------
# exit when any command fails
#Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code. 
set -e

#all other commands

#2------------------------------------------------------------------------

#Other fancy way, by keeping the track of each command

# exit when any command fails
set -e

# keep track of the last executed command
trap &#039;last_command=$current_command; current_command=$BASH_COMMAND&#039; DEBUG
# echo an error message before exiting
trap &#039;echo &quot;\&quot;${last_command}\&quot; command filed with exit code $?.&quot;&#039; EXIT


#3---------------------------------------------------------------------
#With a subs

exit_on_error() {
    exit_code=$1
    last_command=${@:2}
    if [ $exit_code -ne 0 ]; then
        &gt;&amp;2 echo &quot;\&quot;${last_command}\&quot; command failed with exit code ${exit_code}.&quot;
        exit $exit_code
    fi
}

# enable !! command completion
set -o history -o histexpand</code>]]></description>
	<dc:creator>Jit</dc:creator>
</item>

</channel>
</rss>