Перейти к содержанию

Shell scripting


row write in begining of a script and show OS to use bash for execute script. Also know as shebang.

#!/usr/bin/env bash

Use echo 'command' >> whenewer you want to write down command to some file. Also, echo can display some messages.

Warning

Don't forget about chmod +x before run script.

Because script can store in directory not described in PATH, runing script from current directory looks like: [sudo] ./scriptname

Variables in script work like variables in bash.

Sripts may run with parameters. In that case, value of parameters can be obtainted by $1, $2,..., $n for parameters from 1st to n.

Use read command to add interactivity to the script.

Don't forget about 2> /dev/null to filter unnecessary information.

Logical operator if in bash must be end by keyword fi:

if -> then -> [elif -> then] -> [else] -> fi

Use if ! to reverse result of if operator.

Bash has exit code of every command has been ran. Exit code it's a integer number from 0 to 255, where 0 mean "Exit with no errors".
Use $? to see exit code of last operation.

&& - and

|| - or

Comparision in bash execute with special operator - square brakets. For example, if need to compare exit code and run commands depending on the result of comparision:

if [ "$value" = data ] || [ "$value" = almost_data ]
    echo 'Value has data``'
else
    echo 'Value not has data``'
fi

command [ -z $SOME_VARIABLE ] compare lenght of $SOME_VARIABLE with 0 (-z mean Zero lenght)

command [-f $SOME_FILE ] check if the $SOME_FILE exists

Instead "return" shell use exit $EXIT_CODE keyword to exit from script.

Warning

Don't forget about spaces between brackets.

To run multiple commands in one row, use ; after each command.