Shell Free CheatSheet


- PDF Link: cheatsheet-shell-A4.pdf, Category: languages
- Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-shell-A4
- Related posts: Vim CheatSheet, #denny-cheatsheets
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/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 |
Shell run curl check | code/curl-test.sh |
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
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.