Using CheatSheets To Apply Best Practices

Shell Free CheatSheet

Shell Free 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
Shell match regexp echo $str, then grep "$regexp"
Shell match regexp expr match "$date" "^[0-9]\{8\}" >/dev/null && echo yes
Run static code check Link: shellcheck
Show date in utc date -u
Check file type of a given type file /etc/hosts
Check command type of a command type echo

1.2 Shell script

Name Comment
Trap exit signal code/
Shell retry code/
Check if a string contains a substring code/
Check if a string in a list code/, Link: stackoverflow
Log with timestamp code/
Quit if current user is not root code/
Set -x on fly code/
Shell run curl check code/

1.3 Environment variables

Name Comment
List all environment variables export
Define a new env variable export NAME1=”value1″
Define a variable with default value of others export MYVAR=”${MYVAR:-$OTHERVAR}”

1.4 iterm

Name Comment
Delete a word Ctrl+w

1.5 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.6 GNU tools

1.6.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.7 Shell Basic

1.7.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.7.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.7.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.8 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.9 More Resources

License: Code is licensed under MIT License.


2 DONE /usr/bin/time -f “mem=%K RSS=%M elapsed=%E cpu.sys=%S .user=%U” date

Leave a Reply

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