Master Your Terminal: The Ultimate Bash Keyboard Shortcuts & Commands Cheat Sheet
Shortcuts and History
-
Ctrl + A — move to beginning of line
-
Ctrl + B — moves backward one character
-
Ctrl + C — halts the current command
-
Ctrl + D — deletes one character backward or logs out of current session, similar to exit
-
Ctrl + E — moves to end of line
-
Ctrl + F — moves forward one character
-
Ctrl + G — aborts the current editing command and ring the terminal bell
-
Ctrl + H — deletes one character under cursor (same as DELETE)
-
Ctrl + J — same as RETURN
-
Ctrl + K — deletes (kill) forward to end of line
-
Ctrl + L — clears screen and redisplay the line
-
Ctrl + M — same as RETURN
-
Ctrl + N — next line in command history
-
Ctrl + O — same as RETURN, then displays next line in history file
-
Ctrl + P — previous line in command history
-
Ctrl + Q — resumes suspended shell output
-
Ctrl + R — searches backward
-
Ctrl + S — searches forward or suspends shell output
-
Ctrl + T — transposes two characters
-
Ctrl + U — kills backward from point to the beginning of line
-
Ctrl + V — makes the next character typed verbatim
-
Ctrl + W — kills the word behind the cursor
-
Ctrl + X — lists the possible filename completions of the current word
-
Ctrl + Y — retrieves (yank) last item killed
-
Ctrl + Z — stops the current command, resume with fg in the foreground or bg in the background
-
Alt + B — moves backward one word
-
Alt + D — deletes next word
-
Alt + F — moves forward one word
-
Alt + H — deletes one character backward
-
Alt + T — transposes two words
-
Alt + . — pastes last word from the last command. Pressing it repeatedly traverses through command history.
-
Alt + U — capitalizes every character from the current cursor position to the end of the word
-
Alt + L — uncapitalizes every character from the current cursor position to the end of the word
-
Alt + C — capitalizes the letter under the cursor. The cursor then moves to the end of the word.
-
Alt + R — reverts any changes to a command you’ve pulled from your history if you’ve edited it.
-
Alt + ? — list possible completions to what is typed
-
Alt + ^ — expand line to most recent match from history
-
Ctrl + X then ( — start recording a keyboard macro
-
Ctrl + X then ) — finish recording keyboard macro
-
Ctrl + X then E — recall last recorded keyboard macro
-
Ctrl + X then Ctrl + E — invoke text editor (specified by $EDITOR) on current command line then execute results as shell commands
-
Ctrl + A then D — logout from screen but don't kill it, if any command exist, it will continue
-
BACKSPACE — deletes one character backward
-
DELETE — deletes one character under cursor
-
history— shows command line history -
!!— repeats the last command -
!<n>— refers to command line 'n' -
!<string>— refers to command starting with 'string' -
esc :wq— exits and saves script -
exit— logs out of current session
Bash Basics
env— displays all environment variablesecho $SHELL— displays the shell you're usingecho $BASH_VERSION— displays bash versionbash— if you want to use bash (type exit to go back to your previously opened shell)whereis bash— locates the binary, source and manual-page for a commandwhich bash— finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)clear— clears content on window (hide displayed lines)
File Commands
ls— lists your files in current directory, ls<dir>to print files in a specific directoryls -l— lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modifiedls -a— lists all files in 'long format', including hidden files (name beginning with '.')ln -s <filename> <link>— creates symbolic link to filereadlink <filename>— shows where a symbolic links points totree— show directories and subdirectories in easily readable file treemc— terminal file explorer (alternative to ncdu)touch <filename>— creates or updates (edit) your filemktemp -t <filename>— make a temp file in /tmp/ which is deleted at next boot (-d to make directory)cat <filename>— displays file raw content (will not be interpreted)cat -n <filename>— shows number of linesnl <file.sh>— shows number of lines in filecat filename1 > filename2— Copy filename1 to filename2cat filename1 >> filename2— merge two files texts togetherany_command > <filename>— '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)more <filename>— shows the first part of a file (move with space and type q to quit)head <filename>— outputs the first lines of file (default: 10 lines)tail <filename>— outputs the last lines of file (useful with -f option) (default: 10 lines)vim <filename>— opens a file in VIM (VI iMproved) text editor, will create it if it doesn't existmv <filename1> <dest>— moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming))cp <filename1> <dest>— copies a filerm <filename>— removes a filefind . -name <name> <type>— searches for a file or a directory in the current directory and all its sub-directories by its namediff <filename1> <filename2>— compares files, and shows where they differwc <filename>— tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to output only 1 of those informationssort <filename>— sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order.sort -t -k <filename>— sorts the contents on specific sort key field starting from 1, using the field separator t.rev— reverse string characters (hello becomes olleh)chmod -options <filename>— lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID)gzip <filename>— compresses files using gzip algorithmgunzip <filename>— uncompresses files compressed by gzipgzcat <filename>— lets you look at gzipped file without actually having to gunzip itlpr <filename>— prints the filelpq— checks out the printer queuelprm <jobnumber>— removes something from the printer queuegenscript— converts plain text files into postscript for printing and gives you some options for formattingdvips <filename>— prints .dvi files (i.e. files produced by LaTeX)grep <pattern> <filenames>— looks for the string in the filesgrep -r <pattern> <dir>— search recursively for pattern in directoryhead -n file_name | tail +n— Print nth line from file.head -y lines.txt | tail +x— want to display all the lines from x to y. This includes the xth and yth lines.sed 's/<pattern>/<replacement>/g' <filename>— replace pattern in file with replacement value to std output the character after s (/) is the delimitersed -i 's/<pattern>/<replacement>/g' <filename>— replace pattern in file with replacement value in placeecho "this" | sed 's/is/at/g'— replace pattern from input stream with replacement value
Directory Commands
mkdir <dirname>— makes a new directoryrmdir <dirname>— remove an empty directoryrmdir -rf <dirname>— remove a non-empty directorymv <dir1> <dir2>— rename a directory from<dir1>to<dir2>cd— changes to homecd ..— changes to the parent directorycd <dirname>— changes directorycp -r <dir1> <dir2>— copy<dir1>into<dir2>including sub-directoriespwd— tells you where you currently arecd ~— changes to home.cd -— changes to previous working directory
SSH, System Info and Network Commands
ssh user@host— connects to host as userssh -p <port> user@host— connects to host on specified port as userssh-copy-id user@host— adds your ssh key to host for user to enable a keyed or passwordless loginwhoami— returns your usernamesu <user>— switch to a different usersu -— switch to root, likely needs to be sudo su -sudo <command>— execute command as the root userpasswd— lets you change your passwordquota -v— shows what your disk quota isdate— shows the current date and timecal— shows the month's calendaruptime— shows current uptimew— displays who is onlinefinger <user>— displays information about useruname -a— shows kernel informationman <command>— shows the manual for specified commandinfo <command>— shows another documentation system for the specific commandhelp— shows documentation about built-in commands and functionsdf— shows disk usagedu <filename>— shows the disk usage of the files and directories in filename (du -s give only a total)resize2fs— ext2/ext3/ext4 file system resizerlast <yourUsername>— lists your last loginsps -u yourusername— lists your processeskill <PID>— kills the processes with the ID you gavekillall <processname>— kill all processes with the nametop— displays your currently active processeslsof— lists open filesbg— lists stopped or background jobs ; resume a stopped job in the backgroundfg— brings the most recent job in the foregroundfg <job>— brings job to the foregroundping <host>— pings host and outputs resultswhois <domain>— gets whois information for domaindig <domain>— gets DNS information for domaindig -x <host>— reverses lookup hostwget <file>— downloads filenetstat— Print network connections, routing tables, interface statistics, masquerade connections, and multicast membershipstime <command>— report time consumed by command execution
Variables
-
varname=value— defines a variable -
varname=value command— defines a variable to be in the environment of a particular subprocess -
echo $varname— checks a variable's value -
echo $$— prints process ID of the current shell -
echo $!— prints process ID of the most recently invoked background job -
echo $?— displays the exit status of the last command -
read <varname>— reads a string from the input and assigns it to a variable -
read -p "prompt" <varname>— same as above but outputs a prompt to ask user for value -
column -t <filename>— display info in pretty columns (often used with pipe) -
let <varname> = <equation>— performs mathematical calculation using operators like +, -, *, /, % -
export VARNAME=value— defines an environment variable (will be available in subprocesses) -
export -f <funcname>— Exports function 'funcname' -
export var1="var1 value"— Export and assign in the same statement -
export <varname>— Copy Bash variable -
declare -x <varname>— Copy Bash variable -
array[0]=valA— how to define an array -
array[1]=valB -
array[2]=valC -
array=([2]=valC [0]=valA [1]=valB)— another way -
array=(valA valB valC)— and another -
${array[i]}— displays array's value for this index. If no index is supplied, array element 0 is assumed -
${#array[i]}— to find out the length of any element in the array -
${#array[@]}— to find out how many values there are in the array -
declare -a— the variables are treated as arrays -
declare -f— uses function names only -
declare -F— displays function names without definitions -
declare -i— the variables are treated as integers -
declare -r— makes the variables read-only -
declare -x— marks the variables for export via the environment -
declare -l— uppercase values in the variable are converted to lowercase -
declare -A— makes it an associative array -
${varname:-word}— if varname exists and isn't null, return its value; otherwise return word -
${varname:word}— if varname exists and isn't null, return its value; otherwise return word -
${varname:=word}— if varname exists and isn't null, return its value; otherwise set it word and then return its value -
${varname:?message}— if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script -
${varname:+word}— if varname exists and isn't null, return word; otherwise return null -
${varname:offset:length}— performs substring expansion. It returns the substring of $varname starting at offset and up to length characters -
${variable#pattern}— if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest -
${variable##pattern}— if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest -
${variable%pattern}— if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest -
${variable%%pattern}— if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest -
${variable/pattern/string}— the longest match to pattern in variable is replaced by string. Only the first match is replaced -
${variable//pattern/string}— the longest match to pattern in variable is replaced by string. All matches are replaced -
${#varname}— returns the length of the value of the variable as a character string -
*(patternlist)— matches zero or more occurrences of the given patterns -
+(patternlist)— matches one or more occurrences of the given patterns -
?(patternlist)— matches zero or one occurrence of the given patterns -
@(patternlist)— matches exactly one of the given patterns -
!(patternlist)— matches anything except one of the given patterns -
$(UNIX command)— command substitution: runs the command and returns standard output -
typeset -l <x>— makes variable local -<x>must be an integer
Functions
function functname() {
shell commands
}
Related Posts in Series
Collapse- 1. Conventional Commits Cheatsheet
- 2. Commonly Used Regular Expressions (Regex) Cheat Sheet
- 3. Git Cheat Sheet - Most Used Commands
- 4. CSS Selectors Cheat Sheet - Complete Reference
- 5. Master Your Terminal: The Ultimate Bash Keyboard Shortcuts & Commands Cheat Sheet