bash - linux

Comprehensive cheatsheet

A more comprehensive cheatsheet can be found here:

    https://devhints.io/bash
        

Scripting flags template

a_flag=''
b_flag=''
files=''
verbose='false'

print_usage() {
    printf "Usage: ..."
}

while getopts 'abf:v' flag; do
    case "${flag}" in
    a) a_flag='true' ;;
    b) b_flag='true' ;;
    f) files="${OPTARG}" ;;
    v) verbose='true' ;;
    *) print_usage
        exit 1 ;;
    esac
done
        

Read lines

cat /path/to/file | while read line; do
    echo $line
done

echo "line1\nline2\nline3" | while read line; do
    echo $line
done
        

For loops

# both start and end values are included; 2 is the step size
for i in {0..6..2}; do
    echo $i
done

or

for ((i = 0 ; i < 100 ; i++)); do
  echo $i
done
        

Expansions

Brace Expansions
echo {A,B,C}.js  # A.js B.js C.js
echo {1..5}.js   # 1.js 2.js 3.js 4.js 5.js

Access previous commands
!$   # Expand last parameter of most recent command
!*   # Expand all parameters of most recent command
!-n  # Expand nth most recent command
!n   # Expand nth command in history

Example usage
echo !$  # echo {1..5}.js
        

Add colors to text

termcols=$(tput cols)
    bold="$(tput bold)"
    underline="$(tput smul)"
    standout="$(tput smso)"
    normal="$(tput sgr0)"
    black="$(tput setaf 0)"
    red="$(tput setaf 1)"
    green="$(tput setaf 2)"
    yellow="$(tput setaf 3)"
    blue="$(tput setaf 4)"
    magenta="$(tput setaf 5)"
    cyan="$(tput setaf 6)"
    white="$(tput setaf 7)"

echo "${red}THIS IS RED"
        

For each sub-directory in directory

for d in */ ; do
    echo "$d"
done
        

Move (or copy) files, recursing through source directory

# This will copy, starting from the current directory, all files that match *.html pattern
mv */*.html /path/to/dir
        

Default variable if none passed

myVar=${1:-this-is-the-default}
        

Return value from function

myfunc() {
    echo $variable
}
        

Function Gotcha's

  • If you are returning a variable from the function, make sure you have no echos anywhere else in the function.
    They will also be interpreted as output

Copy using xclip from inside a script

    # xclip selection -c
    cat $BASE_DIR$directory_addition$i/$file | xclip -selection c