A memo on useful commands to create a bash script.
To affect the output of a shell command, youcan use $(
or
or better, to respect carriage returns if the variable contains some:
-> Display"4" if a="test"
You can use the expressions: ${variable:position} ou ${variable:position:length}
-> Display"st" if a="test", because it returns the last X characters.
-> Display"es" if a="test" because a substring starts at offset 0.
-> Increase the variable i by 1
-> Displays the 2 elements
The following expression can be used to directly replace characters, by searching/replacing the first occurrence found : ${variable/search/replace}
-> Display "thzs is a value"
To perform multiple replacements, add a second slash after the variable name : ${variable//search/replace}
With substitution, you can convert a variable to uppercase:
Also in lowercase:
There are variables already predefined by the bash interpreter, the most interesting of which are:
Nom | Description |
---|---|
$HOME | User's home directory |
$PATH | Value of environnement variable PATH, which contains search paths |
$$ | Process PID |
$PPID | Parent process PID |
$I | Child process PID |
$PWD | Current folder (may be different from the script path) |
$SECONDS | Number of seconds since shell start |
$? | Return code of the previous command |
or
or
To perform a calculation, it must be surrounded by the tags: $(( <calculation> ))
echo $((4+3))
Operator | Description | Example |
---|---|---|
= | Equality | if [ my_variable = "b" ] |
!= | Difference | if [ my_variable != "b" ] |
-z | Is empty | if [ -z my_variable ] |
-n | Is not empty | if [ -n my_variable ] |
Operator | Description | Mathematical equivalent | Example |
---|---|---|---|
-eq | Equality | = | if [ var1 -eq var2 ] |
-ne | Difference | <> | if [ var1 -ne var2 ] |
-gt | Greater than | > | if [ var1 -gt var2 ] |
-ge | Greater or equal | >= | if [ var1 -ge var2 ] |
-lt | Lesser than | < | if [ var1 -lt var2 ] |
-le | Lesser or equal | <= | if [ var1 -le var2 ] |
The case
It is possible to test several variables, like this:
You can use the logical functions NOT, AND, OR with the comparisons. Note that for the logical operators AND and OR, where the conditions are combined, the square brackets must be doubled.
Fonction | Description | Exemple |
---|---|---|
! | NOT: inverts the direction of the test | if [ ! ${a} = ${b} ] |
&& | AND: combines several mandatory conditions | if [[ ${a} = ${b} && ${b} = ${c} ]] |
|| | OR: combines several optional conditions | if [[ ${a} = ${b} || ${b} = ${c} ]] |
In the above case, we use the seq command, which creates a sequence from 1 to 5.
You have to use -nt and -ot between two files to compare the modification dates of two files :
If you called a program, you can retrieve its return code right after execution and send it back to the caller, like this:
If you want to write the value of a variable on several lines, suffix each line with "\", as below:
RSS | Informations |