Moving and Navigating:
- CTRL+A: Moves the cursor to the beginning of the current line.
- CTRL+B: Shifts the cursor one character backward.
- CTRL+C: Interrupts the current command’s execution.
- CTRL+D: Removes the character before the cursor or logs out of the session (like “exit”).
- CTRL+E: Moves the cursor to the end of the current line.
- CTRL+F: Advances the cursor one character forward.
- CTRL+G: Aborts the current editing action and triggers a terminal bell.
- CTRL+H: Deletes the character under the cursor (similar to DELETE).
- CTRL+J: Performs the same action as pressing RETURN/Enter.
- CTRL+K: Deletes (kills) text from the cursor to the end of the line.
- CTRL+L: Clears the screen and displays the current line.
- CTRL+M: Functions like pressing RETURN/Enter.
- CTRL+N: Moves to the next line in command history.
- CTRL+O: Performs the same action as RETURN/Enter and displays the next line from history.
- CTRL+P: Moves to the previous line in command history.
- CTRL+Q: Resumes suspended shell output.
- CTRL+R: Searches backward in command history.
- CTRL+S: Searches forward or suspends shell output.
- CTRL+T: Swaps the positions of two characters.
- CTRL+U: Deletes (kills) text backward from the cursor to the beginning of the line.
- CTRL+V: Inserts the next character typed verbatim.
- CTRL+W: Deletes (kills) the word before the cursor.
- CTRL+X: Lists possible filename completions for the current word.
- CTRL+Y: Yanks (retrieves) the most recently killed item.
- CTRL+Z: Stops the current command and can be resumed with fg (foreground) or bg (background).
ALT Key Combinations:
- ALT+B: Moves the cursor backward one word.
- ALT+D: Deletes the next word.
- ALT+F: Advances the cursor forward one word.
- ALT+H: Deletes the character before the cursor.
- ALT+T: Swaps the positions of two words.
- ALT+.: Pastes the last word from the previous command, cycling through command history.
- ALT+U: Capitalizes every character from the cursor to the end of the word.
- ALT+L: Converts every character from the cursor to the end of the word to lowercase.
- ALT+C: Capitalizes the character under the cursor and moves to the word’s end.
- ALT+R: Reverts changes to a command from history if edited.
- ALT+?: Lists possible completions for the current input.
- ALT+^: Expands the line to the most recent match from history.
Keyboard Macros and Editing:
- CTRL+X ( ): Starts and stops recording a keyboard macro.
- CTRL+X E: Recalls the last recorded keyboard macro.
- CTRL+X CTRL+E: Invokes the text editor specified by $EDITOR on the current command line and executes the result as shell commands.
- CTRL+A D: Logs out from the screen without terminating any existing commands.
Deleting and Exiting:
- BACKSPACE: Deletes the character before the cursor.
- DELETE: Deletes the character under the cursor.
Command History and Repeating:
- history: Displays the command line history.
- !!: Repeats the last command.
- !<n>: Refers to the command line with index ‘n’.
- !<string>: Refers to the command starting with ‘string’.
Exiting:
- esc :wq: Exits the text editor and saves changes.
- exit: Logs out of the current session.
##################################################
- Display Environment Variables:
- View all the environment variables set in your shell session using the command
env.
- View all the environment variables set in your shell session using the command
- Check Shell and Version:
- Identify the current shell being used with
echo $SHELL. - Determine the version of Bash in use by running
echo $BASH_VERSION.
- Identify the current shell being used with
- Switch to Bash or Return:
- Change your shell to Bash temporarily by typing
bash(exit usingexit). - Locate the binary, source, and manual-page of a command using
whereis bash. - Find the program executed as ‘bash’ with
which bash.
- Change your shell to Bash temporarily by typing
- Clear the Terminal:
- Clear the contents displayed on the terminal screen using the
clearcommand.
- Clear the contents displayed on the terminal screen using the
- List Files and Directories:
- List files in the current directory using
ls, or specify a directory withls <dir>. - Display detailed information, including permissions and ownership, with
ls -l. - List all files, including hidden ones, using
ls -a.
- List files in the current directory using
- Symbolic Links and File Trees:
- Create a symbolic link to a file with
ln -s <filename> <link>. - View the target of a symbolic link using
readlink <filename>. - Display the directory structure in a readable tree format with
tree.
- Create a symbolic link to a file with
- File Operations and Exploration:
- Use the Midnight Commander file explorer in the terminal with
mc. - Create or update a file using
touch <filename>. - Generate temporary files or directories using
mktemp -t <filename>.
- Use the Midnight Commander file explorer in the terminal with
- File Content Manipulation:
- Display the raw content of a file using
cat <filename>. - Add line numbers to the content with
cat -n <filename>. - Show the number of lines in a file using
nl <file.sh>.
- Display the raw content of a file using
- File Merging and Redirection:
- Copy the content of
filename1tofilename2usingcat filename1 > filename2. - Append the content of
filename1tofilename2withcat filename1 >> filename2. - Redirect the standard output of a command to a file using
any_command > <filename>.
- Copy the content of
- Paging and Viewing Files:
- Display the beginning of a file using
more <filename>(scroll with space, quit withq). - Output the first lines of a file with
head <filename>(default: 10 lines). - View the last lines of a file using
tail <filename>(use-ffor real-time updates).
- Display the beginning of a file using
- Text Editing and Manipulation:
- Open and edit a file using the VIM text editor with
vim <filename>.
- Open and edit a file using the VIM text editor with
- File and Directory Management:
- Move a file to a specified destination with
mv <filename1> <dest>. - Copy a file to a destination using
cp <filename1> <dest>. - Remove a file using
rm <filename>.
- Move a file to a specified destination with
- File Searching and Comparison:
- Search for files or directories by name using
find . -name <name> <type>. - Compare two files and display differences with
diff <filename1> <filename2>.
- Search for files or directories by name using
- File Size and Sorting:
- Determine the line, word, and character count of a file with
wc <filename>. - Sort the lines of a text file alphabetically using
sort <filename>(add-nfor numeric,-rfor reverse). - Sort based on a specific field using
sort -t -k <filename>.
- Determine the line, word, and character count of a file with
- String Manipulation and Permissions:
- Reverse the characters of a string using
rev. - Modify file permissions using
chmod -options <filename>.
- Reverse the characters of a string using
- File Compression and Printing:
- Compress files using the gzip algorithm with
gzip <filename>. - Decompress gzip-compressed files with
gunzip <filename>. - View the contents of a gzipped file without decompressing using
gzcat <filename>. - Print a file using
lpr <filename>. - Check the printer queue status with
lpq. - Remove a job from the printer queue using
lprm <jobnumber>.
- Compress files using the gzip algorithm with
- File Conversion and Text Search:
- Convert plain text files into postscript format with
genscript. - Print .dvi files produced by LaTeX using
dvips <filename>. - Search for a specific pattern in files using
grep <pattern> <filenames>or recursively in a directory withgrep -r <pattern> <dir>.
- Convert plain text files into postscript format with
- Extracting Lines and Replacing Text:
- Extract and display a range of lines from a file using
head -n file_name | tail +norhead -y lines.txt | tail +x. - Replace a pattern with a replacement value in a file using
sed 's/<pattern>/<replacement>/g' <filename>, or in-place usingsed -i 's/<pattern>/<replacement>/g' <filename>. - Replace a pattern from input using
echo "this" | sed 's/is/at/g'.
- Extract and display a range of lines from a file using
#####################################################
Directory Commands
- Create a new directory:
mkdir <dirname> - Remove an empty directory:
rmdir <dirname> - Remove a non-empty directory and its contents forcefully:
rmdir -rf <dirname> - Rename a directory from
<dir1>to<dir2>:mv <dir1> <dir2> - Change to the home directory:
cd - Change to the parent directory:
cd .. - Change to a specific directory:
cd <dirname> - Copy
<dir1>and its contents, including sub-directories, into<dir2>:cp -r <dir1> <dir2> - Display the current working directory:
pwd - Change to the home directory:
cd ~ - Change to the previous working directory:
cd -
##############################################################################
SSH, System Info & Network Commands
- SSH:
- Connect to host as user:
ssh user@host - Connect to host on specific port:
ssh -p <port> user@host - Add SSH key to host:
ssh-copy-id user@host
- Connect to host as user:
- System Info:
- Display username:
whoami - Switch user:
su <user> - Switch to root (use
sudo su -):su - - Execute command as root:
sudo <command> - Change password:
passwd - Show disk quota:
quota -v - Display date and time:
date - Show calendar:
cal - View uptime:
uptime - Show online users:
w - Display user info:
finger <user> - Kernel info:
uname -a - Command manual:
man <command> - Alternative documentation:
info <command> - Built-in command help:
help
- Display username:
- Disk and File:
- Show disk usage:
df - Show file/dir disk usage:
du <filename> - Resize file system:
resize2fs
- Show disk usage:
- Process Management:
- Show last logins:
last <yourUsername> - List user processes:
ps -u yourusername - Kill process by PID:
kill <PID> - Kill processes by name:
killall <processname> - Display active processes:
top - List open files:
lsof - Manage jobs:
- List stopped jobs:
bg - Bring job to foreground:
fg - Bring specific job to foreground:
fg <job>
- List stopped jobs:
- Show last logins:
- Network:
- Ping host:
ping <host> - WHOIS lookup:
whois <domain> - DNS info:
dig <domain> - Reverse lookup:
dig -x <host> - Download file:
wget <file> - Network stats:
netstat - Measure command time:
time <command>
- Ping host:
Note: Be cautious when using commands that involve system changes or root access.
########################################################
Variables:
varname=value: Defines a variable.varname=value command: Defines a variable for a subprocess.echo $varname: Checks variable value.echo $$: Prints process ID of current shell.echo $!: Prints ID of recent background job.echo $?: Displays exit status of last command.read varname: Reads input into a variable.read -p "prompt" varname: Reads input with a prompt.let varname = equation: Performs math calculation.export VARNAME=value: Defines an environment variable.export -f funcname: Exports function ‘funcname’.export var1="var1 value": Export and assign.export varname: Copies Bash variable.declare -x varname: Copies Bash variable.${!varprefix*}: Expands to names of variables with specified prefix.${!varprefix@}: Expands to names of variables with specified prefix (array-like syntax).declare -p varname: Display the attributes and value of a variable.typeset -p varname: Same as declare, for compatibility with ksh.
Arrays:
array[0]=valA: Defines an array.array[1]=valBarray[2]=valCarray=([2]=valC [0]=valA [1]=valB): Another way.array=(valA valB valC): Yet another.${array[i]}: Displays array value for index.${#array[i]}: Length of array element.${#array[@]}: Number of values in array.declare -a: Treat variables as arrays.declare -f: Functions only.declare -F: Function names without defs.declare -i: Treat variables as integers.declare -r: Read-only variables.declare -x: Mark variables for export.declare -l: Convert to lowercase.declare -A: Associative array.array+=('new_element'): Add a new element to the end of the array.unset array[index]: Remove an element from the array.${#array[@]}: Number of elements in the array.${array[*]}or${array[@]}: Expands to all elements of the array.${!array[@]}: Expands to indices of the array.array[@]:slice_start:slice_length}: Extract a slice from the array.array[*]:slice_start:slice_length}: Extract a slice from the array (all elements).
Substitution:
${varname:-word}: Return var or word.${varname:word}: Return var or word.${varname:=word}: Return var or set word.${varname:?message}: Return var or error.${varname:+word}: Return word if var.${varname:offset:length}: Substring of var.
Pattern Matching:
${variable#pattern}: Delete short match.${variable##pattern}: Delete long match.${variable%pattern}: Delete short end match.${variable%%pattern}: Delete long end match.${variable/pattern/string}: Replace first match.${variable//pattern/string}: Replace all matches.${variable/pattern/string}: Replace first match of pattern with string.${variable//pattern/string}: Replace all matches of pattern with string.${variable/#pattern/string}: If pattern matches the beginning of variable, replace with string.${variable/%pattern/string}: If pattern matches the end of variable, replace with string.
########################################################
Functions:
function funcname(): Define function.unset -f funcname: Delete function.declare -f: List defined functions.
########################################################
Flow Control:
&&: and operator.||: or operator.-a: and in test conditional.-o: or in test conditional.
File and Directory Tests:
-a file: File exists or compiles.-d file: File exists and is directory.-e file: File exists.-f file: File is regular.-r file: Read permission.-s file: File exists and not empty.-w file: Write permission.-x file: Execute permission.-N file: Modified since last read.-O file: You own file.-G file: Group ID matches yours.file1 -nt file2: file1 newer than file2.file1 -ot file2: file1 older than file2.
#############################################################################
Looping:
for x in {1..10}: Loop with range.for name [in list]: Loop through list.for (( init; cond; update )): Numeric loop.case expr in pattern): Case statement.select name [in list]: Menu select.while condition; do: While loop.until condition; do: Until loop.
Input/Output:
cmd1|cmd2: Pipe output.< file: Input from file.> file: Output to file.>> file: Append to file.|tee <file>: Terminal and file output.
Process Handling:
myCommand &: Run job in background.jobs: List all jobs.fg: Bring job to foreground.kill PID: Terminate process.trap cmd sig1 sig2: Trap signals.disown <PID|JID>: Remove job.wait: Wait for jobs.sleep <number>: Wait seconds.
Debugging:
bash -n scriptname: Syntax check.bash -v scriptname: Echo before.bash -x scriptname: Echo after.trap cmd ERR: Trap errors.trap cmd DEBUG: Trap debug.trap cmd RETURN: Trap return.
#####################################################
COLORS AND BACKGROUNDS
- Reset: Color_Off=’\033[0m’
- Regular Colors:
- Black: Black=’\033[0;30m’
- Red: Red=’\033[0;31m’
- Green: Green=’\033[0;32m’
- Yellow: Yellow=’\033[0;33m’
- Blue: Blue=’\033[0;34m’
- Purple: Purple=’\033[0;35m’
- Cyan: Cyan=’\033[0;36m’
- White: White=’\033[0;97m’
- Additional Colors:
- Light Gray: LGrey=’\033[0;37m’
- Dark Gray: DGrey=’\033[0;90m’
- Light Red: LRed=’\033[0;91m’
- Light Green: LGreen=’\033[0;92m’
- Light Yellow: LYellow=’\033[0;93m’
- Light Blue: LBlue=’\033[0;94m’
- Light Purple: LPurple=’\033[0;95m’
- Light Cyan: LCyan=’\033[0;96m’
- Bold:
- Black: BBlack=’\033[1;30m’
- Red: BRed=’\033[1;31m’
- Green: BGreen=’\033[1;32m’
- Yellow: BYellow=’\033[1;33m’
- Blue: BBlue=’\033[1;34m’
- Purple: BPurple=’\033[1;35m’
- Cyan: BCyan=’\033[1;36m’
- White: BWhite=’\033[1;37m’
- Underline:
- Black: UBlack=’\033[4;30m’
- Red: URed=’\033[4;31m’
- Green: UGreen=’\033[4;32m’
- Yellow: UYellow=’\033[4;33m’
- Blue: UBlue=’\033[4;34m’
- Purple: UPurple=’\033[4;35m’
- Cyan: UCyan=’\033[4;36m’
- White: UWhite=’\033[4;37m’
- Background:
- Black: On_Black=’\033[40m’
- Red: On_Red=’\033[41m’
- Green: On_Green=’\033[42m’
- Yellow: On_Yellow=’\033[43m’
- Blue: On_Blue=’\033[44m’
- Purple: On_Purple=’\033[45m’
- Cyan: On_Cyan=’\033[46m’
- White: On_White=’\033[47m’
Example of usage:
- Use the color variables to change text color and background in Bash scripts.
- Example:
- echo -e “${Green}This is GREEN text${Color_Off} and normal text”
- echo -e “${Red}${On_White}This is Red text on White background${Color_Off}”
- printf “${Red} This is red \n” (option -e is mandatory, it enables interpretation of backslash escapes)


