- PDF Link: cheatsheet-shell-A4.pdf, Category: languages
- Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-shell-A4
- Related posts: Vim CheatSheet, #denny-cheatsheets
File me Issues or star this repo.
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 |
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 |
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}” |
Name | Comment |
---|---|
Delete a word | Ctrl+w |
Name | Comment |
---|---|
Disable all zsh’s autocorrect | In ~/.zshrc, unsetopt correct_all |
Disable a given autocorrect | In ~/.zshrc, alias ssh=’nocorrect ssh’. zsh_disable |
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” |
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 - |
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 |
# 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"
- 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}'
License: Code is licensed under MIT License.