Cheatsheet Bash scripting
Table of Contents
This cheatsheet will have more code snippets on how to do something in bash. It will be a bit different from some other cheatsheets where I show a list of commands.
Basics
echo- print text to the terminalecho Hello world!- prints 'Hello world!'
Variables
COLOR="green"- create variableCOLORand set it to green, you can then use it such as:echo $COLORecho "$COLOR"echo "${COLOR}"echo "My favourite color is $COLOR!"
Arrays
COLORS=("red", "green", "blue")- Define an array of colorsecho ${COLORS[0]}- Print first element in the arrayecho ${COLORS[-1]}- Print last element in the arrayecho ${COLORS[@]}- Prints all elements separated by a spaceecho ${#COLORS[@]}- Prints the number of elements in the array
Loops
For loops:
bash1for item in ${MYLIST[@]}; do2 echo $item3donebash1for ((i=0; i < 10; i++)); do2 echo $i3donebash1for i in {1..10}; do2 echo "Iteration number: $i"3doneWhile loop:
bash1while true; do2 echo "HELLO!"3doneConditionals
Conditionals follow the familiar if statements:
bash1if [ $COLOR != "green" ]; then2 echo "Your favourite color isn't green"3fiYou can use [[ ... ]] to get a status of 0 or 1 depending on the evaluation of the conditional expression inside [[]].
[[ -z STRING ]]- Empty string[[ -n STRING ]]- Not empty string[[ -e FILE ]]- File exists[[ -r FILE ]]- File is readable[[ -d PATH ]]- PATH is a directory[[ -w FILE ]]- File is writeable[[ -s FILE ]]- File size is larger than 0 bytes[[ -x FILE ]]- File is executable[[ STRING == STRING ]]- Both strings are equal[[ STRING != STRING ]]- Strings aren't equal[[ STRING =~ STRING ]]- Test STRING against a regex pattern[[ NUM -eq NUM]]- Both numbers are equal[[ NUM -ne NUM ]]- Numbers aren't equal[[ NUM -lt NUM ]]- First NUM is less than second NUM[[ NUM -le NUM ]]- First NUM is less or equal than second NUM[[ NUM -gt NUM ]]- First NUM is greater than second NUM[[ NUM -ge NUM ]]- First NUM is greater or equal than second NUM[[ ! EXPRESSION ]]- Not[[ EXPRESSION && EXPRESSION ]]- And[[ EXPRESSION || EXPRESSION ]]- Or
References
Webmentions
0 Like 0 Comment



