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
Did you know you can test bash scripts line by line? Well,
The content of the bash script is:
#bash #sh #shell #scripting #debug #debugging
bash -x
is here to help:$ bash -x your_script.sh
+ a=10
+ echo 10
10
The content of the bash script is:
#!/bin/bash
a=10
echo $a
#bash #sh #shell #scripting #debug #debugging
Array and loop in bash script
To define an array you can use a structure like below, be careful that we don't use comma in between:
dbs=( 'test1' 'test2' 'test3' )
Now to loop over the array elements use
for
:for your_db in ${dbs[@]}
do
echo $your_db
done
This is it!
#bash #scripting #for #loop #array