Bash

  • command or error
    <command> || {
        echo "Please install <package>"
        exit 1
    }
    

arrays Link to heading

  • defining: fruits=("apple" "banana" "cherry")
  • accessing by index: echo "${fruits[0]}"
  • accessing all: echo "${fruits[@]}"
  • length: echo "${#fruits[@]}"
  • concatenating: echo "${fruits[*]}"
  • appending: fruits+=("durian")
  • appending multiple: fruits+=("durian" "elderberry")
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"
# apple

for f in "${fruits[*]}"; do
    echo "$f"
done
# apple banana cherry

more_fruits=("durian" "elderberry")
fruits+=("${more_fruits[@]}")

for f in "${fruits[@]}"; do
    echo "$f"
done
# apple
# banana
# cherry
# durian
# elderberry

if Link to heading

if [[ <condition> ]]; then
    <command>
elif [[ <condition> ]]; then
    <command>
else
    <command>
fi

Conditions Link to heading

Files/dirs Link to heading

  • [[ -e <file> ]] file exists
  • [[ -d <dir> ]] dir exists

Strings Link to heading

  • [[ -z <string> ]] string is empty
  • [[ -n <string> ]] string is not empty

Loops Link to heading

for Link to heading

fruits=("apple" "banana" "cherry")
for f in "${fruits[@]}"; do
    echo "$f"
done

sed Link to heading

  • insert a line at the beginning of a file
    sed -i '1i\<lines>' "<file>"
    
  • find and sed multiple files
    find "<dir>" -type f -exec sed -i "s|<search>|<replace>|" {} +
    

Substitution Link to heading

  • ${<variable>} = variable substitution
    • same as $variable, but useful when doing string manipulation
    • text="hello"
      echo "${text:1:3}"
      # ell
      
  • $(<command>) = command substitution
    • echo "Today is $(date +%Y-%m-%d)"
      ``