Skip to content

Instantly share code, notes, and snippets.

@mehar
Last active May 13, 2018 13:56
Show Gist options
  • Save mehar/18912cf945dd3156446d546927a31dfa to your computer and use it in GitHub Desktop.
Save mehar/18912cf945dd3156446d546927a31dfa to your computer and use it in GitHub Desktop.
Bash Command CheatSheet
# Single Quote ('') vs Double Quote("")
Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
[https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html#Double-Quotes]
# Sort directories by size and print
du -h --max-depth=1 | sort -hr
# Setup ssh key based access
ssh-copy-id user@host
# Replace multiple spaces with one space, will be useful as a precursor to cut generally
sed 's/\s\+/ /g'
# cut and get the nth field
cut -d' ' -f<n>
# JSON query
jq .<expr>
# Running previous commands
# export FCEDIT=vi
# List previous commands
fc -l
# Edit the range of commands interested in, edit commands in vi and go forward
fc <nStart> <nEnd>
#:cq for exiting the fc without running the commands
# Tmux over ssh
ssh -t -X user@host 'tmux attach -t mehar || tmux new-session -s mehar'
# Monitoring disk activity
iostat -x 2
# Monitoring the system
dstat
# Write protection (Even root cannot write)
wpon()
{
chattr -R +i *
chattr -R +i .[A-Za-z0-9]*
}
wpoff()
{
chattr -R -i *
chattr -R -i .[A-Za-z0-9]*
}
# Execute a program periodically, showing output to full screen
watch echo '$$'
# Grep through a compressed file
zgrep CONFIG config.tar.gz
# Bash script record/replay
# script commands spawns a new shell, to stop recording exit the new shell
script -q --timing=time.txt script.log
script -q --timing=time.txt -c "who" script.log
scriptreplay -t time.txt script.log
# Copy with progress
cp -auv src dest
# Run command in subshell
(cd /; ls -l)
# Run group of commands in the same shell
{ ls; ls / } > /tmp/o.out # Sredirects are common to all commands in command-list
# Globbing patterns
# *, ?, [abcd], [a-d]
# String building
INNER_STR="Hello World"
OUTER_STR="Here is my bash $INNTER_STR"
echo ${BASH_VERSION}_and_some_string
# readonly bash vars
readonly MY_VAR="string"
# Print all variables in the current context, Its not that all shells have environment variables, all processes have environment variables
env
set # Prints everything
# Print env of a process
cat /proc/{pid}/envron
# A command in bash could be a 'function', 'alias', 'program' or a 'builtin'
# Sample function
function myfunc {
local varLocal="localVar"
echo $varLocal
echo $1
echo $2
echo $#
}
# Clear a function
unset -f myfunc
unset -v myvar
# Print all functions in scope
declare -f
declare -F # only names
typeset -f/F # typeset [-afFirtx] [-p] name[=value]
# Call a builtin program only
builtin <builtin>
builtin cd /tmp
alias cd=doesnotexist
unalias cd
# You can alias an alias as well
# Grep count occurences
grep -c "regex" Glob
# Redirect stderr to stdout
command_does_not_exist > outfile 2>&1
# Incorrect version 'command_does_not_exist 2>&1 > outfile'
# Bash initialization https://blog.flowblok.id.au/static/images/shell-startup.png
# Command substitution, $() is preferred over backticks (``)
echo "My hostname is $(hostname)"
# Tests
[ false == true ] # you can use single = as well for test, but prefer ==
echo $?
# [, and test are synonyms.
# [ is a shell builtin, thats why you need a space after [
( [ 1 = 1 ] || [ ! '0' = '0' ] ) && [ '2' = '2' ] )
[ 1 = 1 -o ! '0' = '0' -a '2' = '2' ]
# Its always better to use [[ instead of [
unset DOESNOTEXIST
[ ${DOESNOTEXIST} = '' ] # throws error, because it becomes [ = '' ], another alternative people use is [ x${DOESNOTEXIST} = x ]
[[ ${DOESNOTEXIST} = '' ]] # Works as expected
# Unary operators for test, test and [, [[ are synonymous with subtle differences
test -z "$VAR" # Return true if the argument is and empty string or it is unset
test -a file # Return true if the file exists
test -d dir # Return trus if the dir exists
# < operator works on strings
# Use -lt, -gt, -eq, -ne for numbers
if [[ 10 -lt 2 ]]; then echo 'does not compute'; fi
# New lines can be replaced by ;, which indicates end of expression
# Bare if
if grep not_there /dev/null; then echo there; else echo not there; fi
# For loop
for (( i=0; i < 10; i++ ))
do
echo $i
done
for f in $(ls)
do
echo "File $f contains $(cat $f)"
done
# Exit codes
TODO
$$ # Current process id
$! # Previous exist code
set -o errexit # set -e
set -o xtrace # set -x
set -o pipefail
# set +<option> to remove
# The <() operator
diff <(ls dir1) <(ls dir2)
# The >() operator
# TODO
# Subshell is a shell that inherits variables from the parent shell, and whose running is deferred
# until the parentheses are closed
VAR1="original var"
$(
echo "inside subshell"
echo ${VAR1}
VAR1="updated var"
echo ${VAR1}
VAR2="second var"
)
# echo don't print new line
echo -n Hello
# Prompt
PS1 #prompt to print after a command
PS2='I am in the middle of something!>>> ' # Default is >
PS3 # TODO
PS4 # In ‘trace’ mode PS4 is echoed before each line of trace output
# Here docs
cat > a.txt << END
content here
next line
END
# History
!! # rerun prev command
function dateit() {
while read line
do
echo "$line $(date '+ %m-%d-%Y %H:%M:%S')"
done
}
vmstat 1 | dateit
# Trapping signals
cat > trap_exit.sh << END
#!/bin/bash
trap "echo trapped" INT
while :; do sleep 5; done
END
chmod +x trap_exit.sh
# Get out of a process and kill it
Ctrl-Z
kill %1
# Delete a specific entry from known_hosts file
function known_hosts_entry_del () {
if [[ "$#" -ne 1 ]]; then
echo "Usage: ${FUNCNAME[0]} <ip_address>"
return 1
fi
# delete lines matching function argument
sed -i.bak /$1/d ~/.ssh/known_hosts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment