Comprehensive cheatsheet
A more comprehensive cheatsheet can be found here:
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
for i in {0..6..2}; do
echo $i
done
for ((i = 0 ; i < 100 ; i++)); do
echo $i
done
Expansions
echo {A,B,C}.js
echo {1..5}.js
!$
!*
!-n
!n
echo !$
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
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
cat $BASE_DIR$directory_addition$i/$file | xclip -selection c