Basics
This cheat sheet-style guide provides a quick reference to commands and practices commonly used when working Command Line (CLI). This cheat sheet mostly uses bash or zsh.
explainshell demystifies the complex CLI commands. cheat.sh and tldr.sh are also amazing resources for references.
Documentation
Section titled “Documentation”man‑ By default the system documentation/manuals are documented in the man pages
man <COMMAND>help‑ Lists all the internal commands of shell
helpBash structure
Section titled “Bash structure”~/.bashrc‑ configure the shell, define command aliases and set command shell options~/.bash_profile‑ initialization commands that set environment variables, a shell’s prompt~/.bash_logout‑ cleanup operations and other commands that you want the shell to execute whenever a user logs out of a shell~/.bash_aliases‑ if storing many aliases commands
Shell Script
Section titled “Shell Script”set -x # Enable RAW i/oset -v # Enable RAW i/oset -e # abort on error(non‑zero exit code)set -u # detect unset variables
variable=${VARIABLE_NAME:-default} # default value if variable empty$(( (1+1)/5 )) # Arithmetic operation${1..10} # Sequence${var%suffix} # trim a suffix named 'suffix'${var#prefix} # trim a prefix named 'prefix'${foo,bar} # expand into multiple values
diff /etc/hosts <(ssh somehost cat /etc/hosts) # parenthesis to execute a sub‑process{..} # Include code in between this block, as a good practicecat <<EOFtouch somefileecho foo > somefileEOFBash Script strict mode
Section titled “Bash Script strict mode”#!/bin/bashset -euo pipefailIFS=$'\n\t'Redirection
Section titled “Redirection”File Descriptors ‑ every file has an associated number called FD. Default ones are:
0‑ STDIN1‑ STDOUT2‑ STDERR
Types of redirection
>‑ STDOUT redirection to file, overwrites at destination
ls -lrt > test.out>>‑ STDOUT redirection to file, appends at destination
ls -lrt >> test.out<‑ STDIN redirection from a file
wc < input_file.out- File Descriptors based redirection
ls -lrt 2>&1|‑ redirects STDOUT of one command into the STDIN of a second command
ls -lrt | wcNavigation
Section titled “Navigation”Ctrl + a‑ Go to beginningCtrl + e‑ Go to endAlt + b‑ Go back one wordAlt + f‑ Go forward one wordCtrl + w‑ Delete a word backwardAlt + d‑ Delete next wordCtrl + u‑ Delete to beginning of line OR delete lineCtrl + k‑ Delete to endCtrl + r‑ Search backwards (recursive)Ctrl + s‑ Search forwardsCtrl + l‑ Clears the screenAlt + t‑ Transpose the last 2 words/characters
Job Management
Section titled “Job Management”&‑ background process.Ctrl+z‑ pauses the process temporarily, and places it inSUSPENDEDmode.fg‑ used to bring a background / paused process back to the foreground and continue its execution.bg‑ resume anySUSPENDEDjobs and run them in backgroundjobs‑ check the job status of all the jobskill‑ used for killing a process
Status: SUSPENDED, CONTINUED, RUNNING, STOPPED
sleep 100 & # Run the command as a background processjobs # view all the jobsjobs -l # view all the jobs along with their job ID & process PIDfg %<JOB_ID> # Resume the job in foreground which has the JOB_IDbg %<JOB_ID> # Resume the job in the background which has the JOB_ID# while a job is running:Ctrl+z # Pauses executing of the current running jobCtrl+c # terminates the current executing processOther Linux Commands
Section titled “Other Linux Commands”ls – listing of files
Section titled “ls – listing of files”# --color = enabling coloured output# -l = long listing# -h = human readable Listing of data# -t = sort by time# -R = Recursive listing of directories
# Must use aliases – `.bash_aliases`alias ls='ls -A -F -B --human --color'alias ll='ls -l'alias la='ls -A'alias lh='ls -h'
ls -lrtless – terminal pager
Section titled “less – terminal pager”# -N = Line number enabled# +F = Real Time Monitoring
sudo dmesg | less +Fcat test.txt | lesshead – starting content of the files
Section titled “head – starting content of the files”# -n = number of lines to display from the start# -c = number of bytes to be displayedhead file.txthead -n 10 file.txthead -c 150 file.txttail – end of the content of files
Section titled “tail – end of the content of files”# -f = real time updates as more content is appended to the end of file.# -n = number of lines of tail to be displayedtail file.txttail -f file.logln – soft/hard link
Section titled “ln – soft/hard link”# -s = softlink/symlinkln sourceFileForHardLink hardLinkFileNameWithPathln -s sourceFileForHardLink softLinkFileNameWithPathchmod – change file permissions
Section titled “chmod – change file permissions”- User‑Group‑Others (--- --- ---)
- Read‑Write‑Execute (rwx)
# -R = Recursive# -V = Verbosechmod +x file.txtchmod 600 file.txtchmod u-w file.txtchmod u+x file.txtchown – change the ownership of files
Section titled “chown – change the ownership of files”# -R = Recursive# -V = Verbosechown user:group directorydu – directory usage
Section titled “du – directory usage”# -h = human readabledu -hdf – disk filesystem
Section titled “df – disk filesystem”# -h = human readable# -i = inode listing# --total = total summary# --output = specify the output strategydf -h /procdf -h --output=source,avail,pcent,targetinode – index number
Section titled “inode – index number”- Data structures that keep track of all the files in the filesystem
- all unique inode in a given filesystem
- stores metadata (type, size, group, user, permission, access, change & modification time)
ps – lists all the processes which are running.
Section titled “ps – lists all the processes which are running.”# -A or -e = list all the processes running for all users# -T = processes running with the current terminal(tty)# -f = full listing for the process# -u = filter process for a specific user# -L = List threads for a process PID# -G = List process associated with a group# -C = search process by name as PID is not known# -o = specifies the format for the columns
ps -efps auxps -L <PID>nohup – run process in the background, even when session is logged out, “no hangup”: prevents from receiving SIGHUP signals
Section titled “nohup – run process in the background, even when session is logged out, “no hangup”: prevents from receiving SIGHUP signals”nohup ./example.sh > output.log 2>&1 &nohup python example.py &disown – delete/remove jobs so that it doesn’t send SIGHUP signal
Section titled “disown – delete/remove jobs so that it doesn’t send SIGHUP signal”# -a = removes all the jobs# -h = marks job so that it DOESN’T send SIGHUP when shell receives a SIGHUP signal# -r = deletes running jobdisown -rdisown -h %2disown -akill – kills the running process
Section titled “kill – kills the running process”# -l = lists all the SIG for kill# 1 = HUP – reload a process# 9 = KILL – Force kill a process# 15 = TERM – Graceful kill of processkill PID_NUMBERkill -9 PIDfzf – CLI fuzzy finder
Section titled “fzf – CLI fuzzy finder”rg – ripgrep ‑ recursive grep
Section titled “rg – ripgrep ‑ recursive grep”pandoc – Convert documents
Section titled “pandoc – Convert documents”pandoc README.md --from markdown --to docx -o tmp.docxsort – alphabetical (lowercase < uppercase) / increasing sorting by default
Section titled “sort – alphabetical (lowercase < uppercase) / increasing sorting by default”# -r = reverse order# -n = recognise numerical results# -k = sort based on specific column# -u = remove duplicate entries# -c = check if the file is in sorted format# -M = arrange based on months# -s = stable sort
sort -nr numeric.txtls -l | sort -nk 5sort -c test.txtuniq – remove duplicate entries, must be in sorted format
Section titled “uniq – remove duplicate entries, must be in sorted format”# -c = count frequency# -d = print only the lines which are duplicated# -u = print all unique lines# -i = ignore casesort file2 | uniq -csort file2 | uniq -usort file2 | uniq -cdcut – cut a field out
Section titled “cut – cut a field out”# -f = field to cut# -d = delimiter to use for cuttingcut -d: -f1,6 /etc/passwdls -lrt | cut -d ' ' -f 1wc – word count
Section titled “wc – word count”# -l = number of lines# -w = number of words# -m = number of characterswc -ltr – translate character
Section titled “tr – translate character”# -C = Complement character# -d = delete charactertr A‑Z a‑ztr -d 'e'sed – substitution
Section titled “sed – substitution”sed s/Amazing/super/gi textfile.txtsed s/originalword/replaceword/g filenamesed -n '3,5p' textfile.txtrsync – remote sync
Section titled “rsync – remote sync”# -v = verbose# -r = recursive# -z = compress during transfer# -h = human‑readable# -P or --progress = shows real‑time progressrsync -avzhe ssh --progress /root/pkgs root@127.0.0.1:/root/pkgsrsync -zvh backup.tar.gz /tmp/backups/curl – request URLs
Section titled “curl – request URLs”# -o = save data to a file# -L = follow redirect# -C = resume an interrupted download# -u = authentication# -v = verbose# --headers = specify request headers# -d or --data = POST request body# -X = specify the request type# -k = disable certificate checkingcurl -o logo.png https://reqbin.com/static/img/logo.pngcurl --header 'Host: targetapplication.com' https://192.0.0.1:8080/curl -X POST https://httpbin.org/postOperations with compressed files – zless, zmore, zcat, zgrep
Section titled “Operations with compressed files – zless, zmore, zcat, zgrep”nc & telnet & netstat
Section titled “nc & telnet & netstat”nc -lv 1234 # start a listener on port 1234nc -zv google.com 443 # check if port is opennc -zv 10.0.2.4 1230‑1235 # scanning a port rangetelnet host.com 1234 # connect to the port in the HOSTnetstat -an | grep LISTEN