Basic Bash Bulletpoints
This page have some useful Bash notes I took while learning bash these days. They are mostly for reference as I always forget how to make whiles, for cycles and other small constructs and I always need to DuckDuckGo them on StackOverflow. Also with the search engine and AI vibe coded sludge that these days plague the web, this is my little page to take code that I made myself while trying to genuinely learn this language.
Hopeful you will find this code reference page useful as well.
Make file Executable
chmod +x filename.sh
#!/bin/bash
echo "I am Nijkstral";
#!/bin/bash decorator=🐀 global_var="I am Global" # This is a global variable echo "Print Variable, $global_var!"; my_function() { local local_var="I am Local"; # This is a local variable echo "printing local Variable: $local_var$decorator"; echo "printing global Variable: $global_var$decorator"; } my_function
#!/bin/bash num1=5; num2=10 sum=$((num1 + num2 + 10)) # It can also be difference (-), Product (*), Quotient (/), Modulus (%) echo "The sum is $sum" # 25
Unary Expressions [ * {data1}] / [ ! * {data1} ] (To do the inverse)
Files
| Operator | TRUE if ${data} is |
| -a -e | FILE |
| -d | DIRECTORY |
| -b | BLOCK SPECIAL FILE |
| -c | CHARACTER SPECIAL FILE |
| -f | REGULAR FILE |
| -g | FILE with SET-GROUP-ID bit |
| -g | FILE with SET-USER-ID bit |
| -h -L | SYMBOLIC LINK |
| -k | FILE with STICKY bit |
| -p | NAMED PIPE |
| -r | READABLE FILE |
| -w | WRITABLE FILE |
| -x | EXECUTABLE FILE |
| -s | FILE with non-zero size |
| -G | FILE owned by GROUP ID |
| -O | FILE owned by USER ID |
| -N | FILE modified since last access |
| -S | SOCKET |
| -t | FILE DESCRIPTORS |
-
-o:
TRUE if optname is anabled -
-z:
TRUE if string is empty -
-v:
TRUE if ${data1} has been declared
Binary Expressions: [ {data1} * {data2} ];
-
-nt:
if {data1} is a file that is newer than {data2} -
-ot:
if {data1} is a file that is older than {data2} -
-eq:
Equal to -
-ne:
Not equal to -
-lt:
Less than -
-le:
Less than or equal to -
-gt:
Greater than -
-ge:
Greater than or equal to
Simple IF and Logical Operators
# Basic if statement for Numbers num=15 if [ $num -ne 15 ]; then echo "Number is not 15" elif ( [ $num -gt 10 ] && [ $num -lt 20 ] ) || [ $num -eq 15 ]; then echo "Number is greater than 10" else echo "Number is a Rat number" fi # Check if variable is not setted if [ -z "$animal" ]; then $animal="Default Rat" fi echo $animal
While
# While loop example count=1 while [ $count -le 5 ]; do # instead of "while", you can use "until" to iterate until a condition is meet echo "Count is $count" ((count++)) done
Break and Continue
# Break and continue example for i in {1..5}; do if [ $i -eq 3 ]; then continue fi echo "Number $i" if [ $i -eq 4 ]; then break fi done
Switch
echo -n "Enter an animal!" read ANIMAL echo -n "The official language of ${ANIMAL} is " case ${ANIMAL} in Rat | Mouse) echo "🐀 You choosed rat or mouse!" ;; Rabbit) echo "🐇 You choosed Rabbit!" ;; Horse | "Pony" | Donkey | "Jenny") echo "🐎 You choosed an equine!" ;; *) echo "unknown" ;; esac
Combo example
#!/bin/bash VALUE="admin" case $VALUE in admin) echo "Has admin access" ;;& admin | editor) echo "Can edit content" ;;& admin | editor | viewer) echo "Can view content" ;; esac
Menu
#!/bin/bash options=("Rat" "Deer" "Donkey" "Rabbit" "Slug") PS3="Select an Animal: " select opt in "${options[@]}" echo "choosen animal: ${opt}"
Indexed
#!/bin/bash fruits=("apple" "banana" "cherry") for fruit in "${fruits[@]}"; do echo $fruit done echo "Print first element: ${fruits[0]}"
Associative
#!/bin/bash # Associative array example declare -A colors colors[apple]="red" colors[banana]="yellow" colors[grape]="purple" unset colors[banana] echo ${colors[apple]} # red echo ${colors[grape]} # purple
Array Manipulation
#!/bin/bash # Indexed Array animals=("rabbit" "kangaroo" "elephant") echo "this is the whole Array: ${animals[@]}. Array lenght: ${#animals[@]}"; # "*" Can aslo be used instead of "@" echo "Print first element is: ${animals[0]}. Element lenght: ${#animals[0]}" # Modify Array orignal=("${animals[@]}") # Copy array animals+=(donkey horse) # Add Element animals[0]=bunny # Change Element animals=(${animals[@]/o/owo}) # Find and reaplce on every element unset animals[0] # Delete the first Element (can be used to delete the whole variable) # unset animals[-1] # Delete the last element # # Merge Arrays additionalAnimals=("dolphin" "camel" "zebra") animals=("${animals[@]}" "${additionalAnimals[@]}") # # Sort the list IFS=$'\n' animals=($(sort <<<"${animals[*]}")); unset IFS # # Filter the list animals=($(printf "%s\n" "${animals[@]}" | grep 'do')) # Cycle through echo -e "\nCycling with \e[1;32m'for in'\e[0m" for animal in "${animals[@]}"; do echo $animal done # C-style for loop echo -e "\nCycling with \e[1;32m'C for loop'\e[0m" for ((i = 0; i <= ${#animals[@]}; i++)) do echo "${animals[i]}"; done
printf "%s" "Enter fullname: " read fullname echo $fullname
fullname="Nijkstral" echo $(echo $fullname | grep "Ni")
add_function() {
local first_var=$1
local second_var=$2
local sum=$(($first_var + $second_var))
echo $sum
}
result=$(add_function 5 3)
echo "The sum is $result"
# Function definition function_name(){ local parameter_1=$1 local parameter_2=$2 ... local parameter_n=$n # commands return 7 # Can only return integers, No way to return Strings } # Function call function_name p1 p2 ... pn echo "The return value is ${?}"
String Lenght
parameter="This is a long string made of rats" echo ${#parameter}
Take a specified section of a string
parameter="Only take the first letter then the last!" echo ${parameter:0:1} echo ${parameter:${#parameter}-1:${#parameter}}
Split
STR="ubuntu:debian:fedora:arch" IFS=":" read -r first second third fourth <<< "$STR" echo "$first" echo "$second" echo "$third" echo "$fourth"
Split All
IN="Rabbit.it;Rat.com" arrIN=(${IN//;/ }) echo ${arrIN[1]} # Output: Rat.com
To replace IFs
# Run the second command only if the First SUCCEED (&&) cat non_existent_file.txt && echo "operation succeeded"; # Run the second command only if the First FAIL ❌(&&) cat non_existent_file.txt || echo "operation failed"; # This can be used to turn if [ -z "$animal" ]; then $animal="Default Rat" fi # Into this [ -z "$animal" ] && animal="Default Rat";
See if a directory exists
if [ -d "$DIRECTORY" ]; then # if [ ! -d "$DIRECTORY" ]; If a directory doesn't echo "$DIRECTORY does exist." fi
Don't wait for a command to finish
sleep 5 & echo "Command is already done";
Directories and Files as Array
files=(*) for filename in "${files[@]}"; do echo $filename done
grep
-
Options
-
-x
Match only Whole line -
-E
Use Extended RegExp -
-P
Use Extended RegExp (Perl) -
-o
Show only matched word
-
-x
-
Preset
-
echo "Test String" | grep -E "Test" -
grep -E "Test" fileToSearch.txt
-
Sed [TODO]
- Options -i 's/"//g' Download.txt
Tar
-
Options
-
-c
--Create archive -
-x
--Extract -
-t
Read all file in the archive -
-f
--file=archive-NAME -
-v
--verbose Show the process -
--add-file
=FILE
-
-c
-
Preset
-
tar -cv --file=${ArchiveName} [List] # Create an archive -
tar -xv --file=${ArchiveName} # Extract an archive -
tar -t --file=test.tar # See archive content
-
XZ Useful for files
-
Options
-
-1...9, -1e...9e
# Levels of compression (Will require more RAM the more compressed it is)
-
-1...9, -1e...9e
-
Preset
-
xz [List] # This will leave only the archive -
unxz ${archive} # Uncompress an XZ archive
-
Zip Useful for protected archives
-
Options
-
-r
--recurisve # Include directories -
-e
# Enable (weak) Encryption -
-P
# Insert a password for encryption
-
-r
-
Preset
-
zip [List] # Simple Archive -
zip -Pe {password} -r {ArchiveName} [List] # Archive with password -
unzip ${archive} # Decompress the archive
-
# Source - https://stackoverflow.com/a/16844327 # Posted by demure, modified by community. See post 'Timeline' for change history # Retrieved 2026-04-15, License - CC BY-SA 3.0 RCol='\e[0m' # Text Reset # Regular Bold Underline High Intensity BoldHigh Intens Background High Intensity Backgrounds Bla='\e[0;30m'; BBla='\e[1;30m'; UBla='\e[4;30m'; IBla='\e[0;90m'; BIBla='\e[1;90m'; On_Bla='\e[40m'; On_IBla='\e[0;100m'; # Black Red='\e[0;31m'; BRed='\e[1;31m'; URed='\e[4;31m'; IRed='\e[0;91m'; BIRed='\e[1;91m'; On_Red='\e[41m'; On_IRed='\e[0;101m'; # Red Gre='\e[0;32m'; BGre='\e[1;32m'; UGre='\e[4;32m'; IGre='\e[0;92m'; BIGre='\e[1;92m'; On_Gre='\e[42m'; On_IGre='\e[0;102m'; # Green Yel='\e[0;33m'; BYel='\e[1;33m'; UYel='\e[4;33m'; IYel='\e[0;93m'; BIYel='\e[1;93m'; On_Yel='\e[43m'; On_IYel='\e[0;103m'; # Yellow Blu='\e[0;34m'; BBlu='\e[1;34m'; UBlu='\e[4;34m'; IBlu='\e[0;94m'; BIBlu='\e[1;94m'; On_Blu='\e[44m'; On_IBlu='\e[0;104m'; # Blue Pur='\e[0;35m'; BPur='\e[1;35m'; UPur='\e[4;35m'; IPur='\e[0;95m'; BIPur='\e[1;95m'; On_Pur='\e[45m'; On_IPur='\e[0;105m'; # Purple Cya='\e[0;36m'; BCya='\e[1;36m'; UCya='\e[4;36m'; ICya='\e[0;96m'; BICya='\e[1;96m'; On_Cya='\e[46m'; On_ICya='\e[0;106m'; # Cyan Whi='\e[0;37m'; BWhi='\e[1;37m'; UWhi='\e[4;37m'; IWhi='\e[0;97m'; BIWhi='\e[1;97m'; On_Whi='\e[47m'; On_IWhi='\e[0;107m'; # White echo -e "${Blu}blue ${Red}red ${RCol}etc...."
Reset: \e[0m
| Regular | Bold | Underline | High Intensity | BoldHight Intens | Background | High Intensity Backgrounds | |
| Black | \e[0;30m | \e[1;30m | \e[4;30m | \e[0;90m | \e[1;90m | \e[40m | \e[0;100m |
| Red | \e[0;31m | \e[1;31m | \e[4;31m | \e[0;91m | \e[1;91m | \e[41m | \e[0;101m |
| Green | \e[0;32m | \e[1;32m | \e[4;32m | \e[0;92m | \e[1;92m | \e[42m | \e[0;102m |
| Yellow | \e[0;33m | \e[1;33m | \e[4;33m | \e[0;93m | \e[1;93m | \e[43m | \e[0;103m |
| Blue | \e[0;34m | \e[1;34m | \e[4;34m | \e[0;94m | \e[1;94m | \e[44m | \e[0;104m |
| Purple | \e[0;35m | \e[1;35m | \e[4;35m | \e[0;95m | \e[1;95m | \e[45m | \e[0;105m |
| Cyan | \e[0;36m | \e[1;36m | \e[4;36m | \e[0;96m | \e[1;96m | \e[46m | \e[0;106m |
| White | \e[0;37m | \e[1;37m | \e[4;37m | \e[0;97m | \e[1;97m | \e[47m | \e[0;107m |
