Bash cheat sheet

Load constants from a configuration file

To load constants in a properties file:

source REPLACE_FILE_PATH

Alternatively:

. REPLACE_FILE_PATH

The config file will look like this:

export constant_name_1=”value 1″
export constant_name_2=”value 2″
export constant_name_3=”${constant_name_1}${constant_name_2}”

Check input parameters

Check minimum number of parameters

if [ “$#” -lt “2” ] then
echo “Usage: $0 param_name_1 param_name_2″
exit 1
else

fi

Check first parameter is empty

if [[ -z $1 ]] then
print Usage: “$NAME” param_name
exit
fi

Loops

Fixed number of iterations

for repository_id in {1..7}
do
echo $repository_id
done

Iterate over all the elements of an array

for element_id in ${elements[@]}
do
echo $element_id
done

Iterate over all the files/folder in the current folder

for file in *
do
echo $file
done

Iterate over all the results of a request

results=$(curl -k …)for result in $results
do
echo ${result}
done

Using dynamic variable names

When we have to get the value of a variable whose name is generated automatically we can use: “!”

for index_id in {1..7}
do
variable_name=”name_prefix${index_id}”
echo “Value: ${!variable_name}”

done

Common issues

Error assigning variables

Check there are no blank spaces between the variable name, the “=” symbol and the value

Comparison not working as expected

If it always returns true check the spaces around the comparison symbol

Best practices

https://sharats.me/posts/shell-script-best-practices

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>