Using CheatSheets To Apply Best Practices

Shell CheatSheet

Shell CheatSheet

1.1 Basic

Name Comment
Redirect stdout/stderr ls /tmp >/dev/null 2>&1
Deal with filename basename $f, dirname $f
Use timeout: avoid command hang timeout 10 sh -c ‘ls -lt’
Restart shell without killing terminal exec -l $SHELL
Run sub-shell echo $BASH_SUBSHELL; ( echo "Running in subshell: $BASH_SUBSHELL" )
Set pipefail set -ueoxv pipefail, set +ueoxv pipefail
Run static code check Link: shellcheck

1.2 Shell script

Name Comment
Trap exit signal code/trap-exit.sh
Shell retry code/shell-retry.sh
Check if a string contains a substring code/string-contains.sh
Check if a string in a list code/string-in-list.sh, Link: stackoverflow
Log with timestamp code/log-with-timestamp.sh
Quit if current user is not root code/assert-user-root.sh
Set -x on fly code/restore-debug-output.sh

1.3 Environment variables

Name Comment
List all environment variables export
Define a new env variable export NAME1=”value1″

1.4 zsh

Name Comment
Disable all zsh’s autocorrect In ~/.zshrc, unsetopt correct_all
Disable a given autocorrect In ~/.zshrc, alias ssh=’nocorrect ssh’. zshdisable

1.5 GNU tools

1.5.1 Echo string

Name Comment
Echo red text echo -e “hello,\e[0;31m there \e[0;31m”
Echo multiple lines echo -e “hello,\ndenny”
Echo bold text echo -e hello, “\033[1mThis is bold text.\033[0m”
Echo underlined text echo -e hello, “\033[4mThis is underlined text.\033[0m”

1.6 Shell Basic

1.6.1 cd

Name Comment
Go to given folder cd /var/log/
Go to folder in subshell (cd /var/log/ && ls) After this, PWD won’t be changed
Go to home cd
Go to parent folder cd ..
Go to previous folder cd -

1.6.2 Numeric

Name Comment
* expr 5 \* 4
+ let z=x+y, z=$x+$y
== int1 -eq int2, [ $? -eq 0 ] && echo "good"
>= int1 -ge =int2
> int1 -gt =int2
<= int1 -le =int2
< int1 -lt =int2
!= int1 -ne =int2

1.6.3 xargs

# Run grep for files filtered by find
find /var/log -name "*.log" | xargs grep -i error

# Loop with pipes
cat /etc/passwd | awk -F':' '{print $1}' | xargs -I{} sudo -l -U {} | grep -v "not allowed to"

1.7 Scripts

  • Compare command output
[ 0 -eq $(find ./data -name "*.txt" -type f -print | wc -l) ]

  • get ip from eth0
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

1.8 More Resources

License: Code is licensed under MIT License.

linkedin
github
slack




Leave a Reply

Your email address will not be published. Required fields are marked *