Skip to content

Instantly share code, notes, and snippets.

@bsnux
Created August 12, 2020 23:22
Show Gist options
  • Save bsnux/10b45b8bae91e58577ba5f2d94f41872 to your computer and use it in GitHub Desktop.
Save bsnux/10b45b8bae91e58577ba5f2d94f41872 to your computer and use it in GitHub Desktop.
Simple and quick bash scripting reference
#!/bin/bash
#----------
# simple-cheatsheet.sh
#
# source: https://devhints.io/bash
#
#----------
# Variables
NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}!"
# Conditional execution
git commit && git push
git commit || echo "Commit failed"
## Creating directory if it doesn't exist
dest_dir="/tmp/test"
[[ ! -d $dest_dir ]] && mkdir $dest_dir
# Arrays
fruits=('Apple' 'Banana' 'Orange')
echo ${fruits[0]} # Element #0
echo ${fruits[-1]} # Last element
echo ${fruits[@]} # All elements, space-separated
echo ${#fruits[@]} # Number of elements
echo ${#fruits} # String length of the 1st element
echo ${#fruits[3]} # String length of the Nth element
echo ${fruits[@]:3:2} # Range (from position 3, length 2)
echo ${!fruits[@]} # Keys of all elements, space-separated
for i in "${fruits[@]}"; do
echo $i
done
fruits=("${fruits[@]}" "Watermelon") # Push
fruits+=('Watermelon') # Also Push
fruits=( ${fruits[@]/Ap*/} ) # Remove by regex match
unset fruits[2] # Remove one item
fruits=("${fruits[@]}") # Duplicate
fruits=("${fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file
# Dictionaries
declare -A sounds
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"
for val in "${sounds[@]}"; do
echo $val
done
for key in "${!sounds[@]}"; do
echo $key
done
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
echo ${#sounds[@]} # Number of elements
unset sounds[dog] # Delete dog
# Heredoc
cat <<END >production.txt
[my box]
0.0.0.0
END
# Conditionals
## String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
else
echo "This never happens"
fi
## Equal
a="foo"
b="foo"
if [[ "$a" == "$b" ]]; then
echo "equal"
fi
## Regex
a="testing"
if [[ "$a" =~ ^test$ ]]; then
echo "match"
fi
## replacing all
foo="foobarfoobarfoo"
echo ${foo//foo/bar}
## smaller
if (( $a < $b )); then
echo "$a is smaller than $b"
fi
## checking file
if [[ -e "file.txt" ]]; then
echo "file exists"
fi
# Functions
myfunc() {
echo "hello $1"
}
myfunc "Lucas"
#-- returning values
myfunc() {
local myresult='some value'
echo $myresult
}
result="$(myfunc)"
# Ranges
for i in {1..5}; do
echo "Welcome $i"
done
# C-like loop
for ((i = 0 ; i < 100 ; i++)); do
echo $i
done
# Basic loop
for i in /tmp/*; do
echo $i
done
# Reading files line by line
cat file.txt | while read line; do
echo $line
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment