Variables
Basis
myVar=myValueAssign a value to the variable (warning, no space!).
myVar=$(whoami)Assign command output to the variable.
$myVarAccess variable content.
Array
myArray=()Create an empty array.
myArray=( 12 12 )Create an array with values (note the space between values).
myArray[0]=myValueAssign a value to the first value of the array.
myArray+=(myValue)Append value at the end of the array (add a value).
${myArray[0]}Return the first value of the array.
${myArray[@]}Return the whole array.
${myArray[3:@]}Return the values form third to last.
${#myArray[@]}Return the array size.
Special Variables
$?Output code of previously executed program.
$0Path of the currently called script.
$1, $2 ...Arguments passed to the script.
$#Arguments numbers.
$@Return all the arguments.
dateReturn date, time, and time difference.
date "+%H"Return the current hour. (
%H
= hour,%M
= minute,%S
= second, …).
seq 1 12Return a number sequence.
Structures
Condition
if [ boolean ]
then
...
elif
then
...
else
...
fi
For Loop
for i in `seq 0 100`
do
...
done
for i in {1..100}
do
...
done
directories=( myDir1 myDir2 myDir3)
for directory in "${directories[@]}"; do
mkdir -p $directory
...
done
While Loop
# Read lines for file
while read line
do
echo $line
done < myFile
while read line; do echo $line; done < myFile.txtOne liner version of while loop to read file.
Redirections
Chevrons
>Redirects to a file (if it already exists, it will be overwritten).
>>Redirects to the end of a file (if it doesn't exist, it will be created).
2>Redirects errors to a file (if it already exists, it will be overwritten).
2>>Redirects errors to the end of a file (if it doesn't exist, it will be created).
2>&1Redirects errors in the standard output.
< myFileSends a file as a input command.
KEYWORD <<Switches the console to keyboard input mode, line by line. All the lines will be sent when the end keyword has been written.
<<< myStringSends a string as a input command.
Ampersand
cmd1 & cmd2First command will be executed in background.
cmd1 && cmd2Second command is executed if the first command return code is 0 (ok).
Pipe
cmd1 | cmd2Chains commands (output from command 1 is sent to command 2).
cmd1 || cmd2Second command is executed if the first command return code is not 0 (error).