Skip to content

Instantly share code, notes, and snippets.

@bsnux
Last active June 2, 2021 20:42
Show Gist options
  • Save bsnux/d989f26abc87825b0f0d893fe1e4c329 to your computer and use it in GitHub Desktop.
Save bsnux/d989f26abc87825b0f0d893fe1e4c329 to your computer and use it in GitHub Desktop.

Bash cheatsheet

Google Shell Style Guide

Output

echo "Hello World"
printf "Hello World\n"

Format string for printf

  • %s String
  • %d Decimal
  • %f Float
  • %x Hexadecimal
  • \n New line
  • \t Tab

Positional parameters

  • $# Number of parameters
  • $0 Script name
  • $1 First parameter
  • $2 Second parameter

Reading a file

while IFS="" read LINE do
  echo "$LINE"
done < "file.txt"

Assigning shell ouput

cmdoutput=$(ls -l)

If statements

if cond then
  cmd_a
else
  cmd_b
fi

File and numerical conditions

if [[ -e $filename ]] then
  echo "$filename exists"
fi

File test

  • -d Directory exists
  • -e File exists
  • -r File is readable
  • -w File is writable
  • -x File is executable

Numeric test

  • -eq Equal
  • -gt Greater than
  • -lt Less than
a=3
b=1
if [ "$a" -gt "$b" ]; then
  echo "$a is greater"
fi

while loops

i=0
while (( i < 1000 )) do
  let i++
done

for loops

for ((i=0; i < 10; i++)) do
  echo "$i"
done
for item in alice bob tom; do
  echo "$item"
done
for i in $(seq 1 10); do echo $i; done

case statement

case $var in
  "bob")
    echo "Bye Bob!"
    ;;
  "alice")
    echo "Bye Alice!"
    ;;
  "tom")
    echo "Bye Tom!"
    ;;
  *)
    echo "Bye!"
    exit
    ;;
esac

Functions

function hello_friend () {
  name=$1
  echo "Hello $name"
}  

hello_friend "Alice"

Arrays

declare -a files=(
  "/usr/local/etc/php-fpm.d/php-fpm-pool.conf"
  "/etc/nginx/conf.d/test.conf"
  "/usr/local/etc/php/php.ini"
)

for file in "${files[@]}"; do
  echo $file
done

Hashmaps

declare -A hash=(
  [HDD]=Brand1
  [Monitor]=Brand2
  [Keyboard]=Brand3
)

for key in "${!hash[@]}"; do
  echo $key;
done

Search and replace

name="NumberThreeNumberThree"

# All occurrences
filename="${name//Three/3}"

# First occurrence
filename="${name/Three/3}"

echo "$filename"

Heredoc

# Creating a .gitlab-ci.yml in current directory
cat <<EOF > .gitlab-ci.yml
image: busybox:latest
include:
  - template: Security/Secret-Detection.gitlab-ci.yml
test:
  stage: test
  script:
    - /bin/sh -c 'echo "Do nothing"'
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment