Issue
I have the following bash script:
echo one
echo two
cd x
echo three
which fails at the 3rd line as there is no directory named x
. However, after running the script, when I do $?
, 0 is returned, even though the script has an error. How do I detect whether the script ran successfully or not?
Solution
Check the condition of directory existence in the script statements:
[ -d x ] && cd x || { echo "no such directory"; exit 1; }
Or put set -e
after shebang line:
#!/bin/bash
set -e
echo one
echo two
cd x
echo three
Answered By - sungtm Answer Checked By - Gilberto Lyons (WPSolving Admin)