In Linux bash scripting you can check commands exit codes and do appropriate jobs accordingly. For that we will use || and &&.
Let's start by a simple echo command:
If for any reason we want to check the exit code of
You can use code block to run multiple commands:
The is another way that you can check exit code and it is
When
#linux #bash #script #scripting #exit_code
Let's start by a simple echo command:
echo "Hello everybody"
If for any reason we want to check the exit code of
echo
command to see if it is successful or not. We can use the code block:echo "Hello everybody" && echo "Phew! We're good." || echo "echo command FAILED!"
You can use code block to run multiple commands:
echo "Hello everybody" && {
echo "Phew! We're good."
touch ME
} || {
echo "echo command FAILED!"
touch YOURSELF
}
NOTE:
exit code 0 means command execution was successful, and exit code 1 means something nasty happened to the previous command.The is another way that you can check exit code and it is
$?
:cp ME YOURSELF
if [ $? = 0 ] ; then
echo "copy seems OK!"
else
echo "Yuck! File could not get copied! :("
fi
When
cp
command is run $?
will keep the exit code of recent command which has been executed.#linux #bash #script #scripting #exit_code
In
For checking directory existence we use
#bash #linux #directory_existence #file_existence
Linux
we have a command called test
, you can check whether a file/directory exists or not and run commands based on the result. For example let's say we want to check if a folder exists and if it does not exist, create the folder.For checking directory existence we use
test -d
and for file existence we use test -f
, so for our example in order to check if the directory exists we use test -d
and in case the folder does not exists we will create it:directory_to_check="/data/mysql"
test -d $directory_to_check || {
echo "$directory_to_check does not exist, creating the folder..." && mkdir -p $directory_to_check || {
echo "$directory_to_check directory could not be created!"
exit 1
}
}
NOTE:
you can read more about exit codes with hashtag #exit_code#bash #linux #directory_existence #file_existence