Bash Cheat Sheet

Variables and User Input

read -p "What is you name: " name
echo "Hello $name"

read -p "What do you like to do: " verb
echo "You like ${verb}ing"

Expressions

[[ -e "$file" ]] # True if file exists
[[ -d "$file" ]] # True if file exists and is a directory
[[ -f "$file" ]] # True if file exists and is a regular file
[[ -z "$str" ]] # True if string is of length zero
[[ -n "$str" ]] # True is string is not of length zero
# Compare Strings
[[ "$str1" == "$str2" ]]
[[ "$str1" != "$str2" ]]

# Integer Comparisions
[[ "$int1" -eq "$int2" ]] # $int1 == $int2
[[ "$int1" -ne "$int2" ]] # $int1 != $int2
[[ "$int1" -gt "$int2" ]] # $int1 > $int2
[[ "$int1" -lt "$int2" ]] # $int1 < $int2 [[ "$int1" -ge "$int2" ]] # $int1 >= $int2
[[ "$int1" -le "$int2" ]] # $int1 <= $int2

# And / Or

[[ ... ]] && [[ ... ]] # And
[[ ... ]] || [[ ... ]] # Or

Conditionals

# 1. Return values
# If notes.md file doesn't exist, create one and # add the text "created by bash"

if find notes.md
  then echo "notes.md file already exists"
else
  echo "created by bash" | cat >> notes.md
fi
# 2. Arithmetic Evaluations
read -p "Enter your age: " age

if (( "$age" > 18 ))
then
  echo "Adult!"
elif (( "$age" > 12 ))
then
  echo "Teen!"
else
  echo "Kid"
fi
# 3. Test Expressions
# Check if argument was passed
# "$1" corresponds to first argument
if [[ -n "$1" ]]
then
  echo "Your first argument was $1"
else
  echo "No Arguments passed"
fi

Looping

# print numbers 1 to 10

# c like for loop
for (( i = 1; i <= 10; ++i ))
do
  echo "$i"
done

# for in
for i in {1..10}
do
  echo "$i"
done

# while
i=1
while [[ "$i" -le 10 ]]
do
  echo "$i"
  ((i++))
done

# until
i=1
until [[ "$i" -eq 11 ]]
do
  echo "until $i"
  ((i++))
done
# Iterating over arrays

arr=(a b c d)
# For in
for i in "${arr[@]}"
do
  echo "$i"
done

# c like for
for (( i = 0; i < "${#arr[@]}"; i++))
do
  echo "${arr[$i]}"
done

# while
i=0
while [[ "$i" -le "${#arr[@]}" ]]
do
  echo "${arr[$i]}"
(( i++ ))
done

# Iterating over arguments
# @ holds all the arguments passed in to the script
for i in "[email protected]"
do
  echo "$i"
done

Arrays

arr=(a b c d)

echo "${arr[1]}" # Single element
echo "${arr[-1]}" # Last element
echo "${arr[@]:1}" # Elements from 1
echo "${arr[@]:1:3}" # Elements from 1 to 3

# Insert
arr[5]=e # direct address and insert/update
arr=(${arr[@]:0:1} new ${arr[@]:1}) # Adding 'new' to array

# Delete
arr=(a b c d)
unset arr[1]
echo << "${arr[1]}" # Outputs nothing

# Re-Index after Delete
arr=(a b c d)
unset arr[1]
arr=("${arr[@]}")
echo << "${arr[1]}" # c

Functions

greet() {
  echo "Hello, $1"
}

greet Bash # Hello, Bash

# All the arguments of a function can be accessed using @.

greet() {
  echo "Hello, ${@}"
}

greet every single body # Hello, every single body

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.