Bash cheat sheet

This cheat sheet brings together what you need for everyday work in the Bash shell: command-line keyboard shortcuts, history, output redirection and pipes, variables, conditions and loops, scripts, and background jobs. You can search for a command or shortcut, filter by topic, and copy it with one click.

Command-line keyboard shortcuts

  • Ctrl+A

    Moves the cursor to the start of the line.

  • Ctrl+E

    Moves the cursor to the end of the line.

  • Alt+B

    Moves the cursor back one word. When the Alt key doesn't work in your terminal, press Esc and then B.

  • Alt+F

    Moves the cursor forward one word, to the end of the next word.

  • Ctrl+U

    Deletes all the text from the cursor to the start of the line. Useful when you want to type the command again.

  • Ctrl+K

    Deletes the text from the cursor to the end of the line.

  • Ctrl+W

    Deletes the word before the cursor, back to the previous space.

  • Tab

    Completes the name of a command, file, directory, or variable. When there are several options, pressing Tab again shows all of them.

  • Alt+.

    Inserts the last argument of the previous command at the cursor. Each additional press moves to the last argument of an earlier command.

  • Ctrl+L

    Clears the screen and keeps the line you are typing at the top of the screen.

  • Ctrl+C

    Stops the command that is currently running. While you are typing, it cancels the line and opens a new prompt.

  • Ctrl+D

    On an empty line, closes the shell, and over SSH also disconnects you from the server. When the line has text, it deletes the character under the cursor.

Command history

  • Ctrl+R

    Searches the history as you type. Press Ctrl+R again to move to an earlier match, Enter to run the command found, the Right or Left arrow or Esc to end the search and edit the line, and Ctrl+G to cancel.

  • history 20

    Shows the last 20 commands, each with a number.

  • !!

    Runs the previous command again. Especially handy as sudo !! when a command failed because of permissions.

  • !$

    Inserts the last argument of the previous command.

    Example: First command: mkdir -p /var/www/example/logs | Second command: cd !$

  • !120

    Runs command number 120 from the history list again. Caution: the command runs immediately, without confirmation.

  • HISTCONTROL=ignoreboth

    Consecutive duplicate lines and lines that start with a space aren't saved in the history. This lets you type a space before a command that contains a password so it isn't saved. To make the setting permanent, add the line to the ~/.bashrc file.

  • HISTSIZE=10000

    The number of commands the shell keeps in its history. The default is 500. The number of lines in the ~/.bash_history file is set by the HISTFILESIZE variable.

Output redirection and pipes

  • ls -l > list.txt

    Writes the output to a file instead of the screen. Caution: when the file exists, its previous content is erased.

  • date >> run.log

    Appends the output to the end of the file without erasing the existing content. When the file doesn't exist, it is created.

  • ./backup.sh 2> errors.log

    Saves only the error messages to the file, while the regular output still appears on the screen.

  • ./backup.sh > backup.log 2>&1

    Saves the output and the error messages to the same file. The order matters: with 2>&1 > backup.log, error messages still appear on the screen. The short form &> backup.log does the same thing.

  • cat <<'EOF' > notes.txt

    Writes to the file all the lines typed after the command, up to a line that contains only EOF (a construct called a here document). When EOF is in quotes, variables such as $HOME stay as text; without quotes, they are replaced with their values.

  • ls -l /etc | less

    A pipe: the output of the first command becomes the input of the second, here for paging with less.

  • ./backup.sh 2>&1 | tee backup.log

    Shows the output on the screen and saves it to a file at the same time. With tee -a, the output is appended to the end of the file instead of overwriting it.

  • echo "203.0.113.10 example.com" | sudo tee -a /etc/hosts

    Adds a line to a file that requires root permissions. The form sudo echo with >> fails because the redirection is done by your own shell, not under sudo. Caution: without -a, the file is overwritten.

  • set -o noclobber

    Prevents > from overwriting an existing file, and the command fails with an error message. When you do want to overwrite, use >|.

Variables and quoting

  • NAME="example"

    Sets a variable. There are no spaces before or after the equals sign; otherwise, Bash tries to run a command named NAME.

  • echo "Hello $NAME"

    Inside double quotes, variables are replaced with their values. We recommend wrapping variables in double quotes so a value with spaces isn't split into several words.

  • echo 'Hello $NAME'

    Inside single quotes, every character stays as it is, and the variable is shown as text, not as its value.

  • echo "${PORT:-8080}"

    Shows the value of PORT, or 8080 when the variable is unset or empty. The value of PORT itself doesn't change.

  • FILE=/var/www/example/index.php; echo "${FILE##*/}"

    Removes everything up to the last slash and leaves the file name, index.php. The form ${FILE%/*} leaves the directory path.

  • export NAME

    Passes the variable to programs and scripts that the shell starts. A variable that isn't exported is available only in the current shell.

  • APP_ENV=staging ./deploy.sh

    Sets a variable for a single command only. After the command finishes, the variable doesn't remain in the shell.

Command substitution and arithmetic

  • TODAY=$(date +%F)

    Saves the output of a command in a variable, here the date in year-month-day format.

    Example: tar -czf "backup-$TODAY.tar.gz" /var/www/example

  • echo "Files: $(ls | wc -l)"

    Embeds the output of a command in text. The old form with backticks still works, but $(...) is easier to read and recommended.

  • echo $((60 * 24))

    Integer arithmetic. The result here is 1440.

Exit codes and chaining commands

  • echo $?

    Shows the exit code of the last command: 0 means success, and any other number means failure. Code 127 means the command wasn't found, and code 126 means it was found but can't be executed.

  • sudo nginx -t && sudo systemctl reload nginx

    The second command runs only if the first one succeeded. Here, the reload happens only after the configuration test passes.

  • cd /var/www/example || exit 1

    The second command runs only if the first one failed. In a script, the line stops the run when the directory doesn't exist, before the next commands run in the wrong directory.

  • date; uptime

    A semicolon runs the commands one after the other, even when the first one fails.

Filename patterns and brace expansion

  • ls *.log

    The asterisk matches any sequence of characters, here every file in the current directory that ends in .log. Hidden files, whose names start with a dot, aren't included. When nothing matches, the pattern stays as text.

  • echo rm *.tmp

    Shows the full command after the pattern is expanded, without running it. This is how you check which files will be deleted before running rm with a pattern. Caution: rm doesn't move files to a trash folder, and an accidental deletion is permanent.

  • echo {1..5}

    Creates a sequence: 1 2 3 4 5. The form {01..10} adds leading zeros, and the form {a..e} creates a sequence of letters.

  • mkdir -p example/{logs,tmp,public}

    Creates three directories in one command. Brace expansion creates the names even when the files or directories don't exist.

  • cp config.php{,.bak}

    Short for cp config.php config.php.bak, to make a backup copy before editing without typing the name twice.

  • shopt -s globstar

    Turns on the ** pattern, which also matches subdirectories at any depth. For example, ls **/*.conf lists every .conf file in the directory and in all the directories inside it.

One-line conditions and loops

  • for f in *.log; do echo "$f: $(wc -l < "$f")"; done

    Goes over every .log file in the directory and shows how many lines each one has. The quotes around $f keep file names with spaces intact.

  • while IFS= read -r line; do echo "$line"; done < domains.txt

    Reads a file line by line. The IFS= setting keeps spaces at the start of the line, and the -r option stops Bash from interpreting backslashes.

  • if [ -f /etc/nginx/nginx.conf ]; then echo "found"; fi

    Checks whether a regular file exists. You must leave a space after [ and before ].

  • [ -d /var/www/example ] || mkdir -p /var/www/example

    The -d test returns true when the directory exists. Here, the directory is created only when it is missing.

  • [ -z "$NAME" ] && echo "empty"

    The -z test returns true when the string is empty, and the -n test returns true when it isn't empty. Inside [ ], wrap the variable in quotes.

  • [ "$COUNT" -gt 10 ] && echo "more than 10"

    Number comparison: -eq equal, -ne not equal, -lt less than, -le less than or equal, -gt greater than, -ge greater than or equal. To compare strings, use = and !=.

  • [[ $FILE == *.log ]] && echo "log file"

    The [[ ]] form is an extended Bash test: it allows pattern matching with == and regular expression matching with =~, and variables inside it aren't split even without quotes.

Functions, aliases, and configuration files

  • mkcd() { mkdir -p "$1" && cd "$1"; }

    Defines a function that creates a directory and changes into it, for example mkcd /var/www/new. The first argument passed to the function is available in it as $1.

  • alias

    Without parameters, lists all the aliases defined in the current shell.

  • ~/.bashrc

    Read each time an interactive shell that isn't a login shell starts, for example when you run the bash command or open a new terminal window on the desktop. This is the usual place for aliases, functions, and history settings.

  • ~/.bash_profile

    Read in a login shell, for example when you log in over SSH. Bash reads only the first file that exists out of ~/.bash_profile, ~/.bash_login, and ~/.profile, so it is common to load ~/.bashrc from it as well.

    Example: if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

  • . ~/.bashrc

    Reloads the file in the current shell after editing, without logging in again. The dot is the same as the source command.

Scripts

  • #!/usr/bin/env bash

    The first line of a script (the shebang). It makes the script run in Bash, found through the PATH environment variable.

  • chmod +x backup.sh && ./backup.sh

    Gives the script execute permission and runs it. The ./ prefix is needed because the current directory usually isn't in PATH.

  • set -euo pipefail

    A common line at the start of a script: -e stops the script when a command fails, -u stops it when an unset variable is used, and pipefail makes a pipeline return a failure when any command in it fails. The -e option has exceptions, for example a command that is the condition of an if or that comes before && or ||, so it doesn't replace error checking in the script.

  • bash -x backup.sh

    Runs the script and shows each command before it runs, after variables are substituted. Useful for troubleshooting.

  • bash -n backup.sh

    Checks the script's syntax without running it.

  • "$@"

    Inside a script, $1 and $2 are the first and second arguments, $# is the number of arguments, and "$@" passes all of them on, each as a separate word.

  • TMP=$(mktemp); trap 'rm -f "$TMP"' EXIT

    Creates a temporary file and deletes it automatically when the script ends, even when it stops because of an error.

Background jobs

  • Ctrl+Z

    Pauses the command that is currently running and returns you to the prompt. The command isn't terminated, and you continue it with fg or bg.

  • bg

    Continues the paused job in the background, and the terminal stays free for other commands.

  • jobs -l

    Lists the jobs of the current shell, with the process ID (PID) of each one. The + sign marks the current job.

  • kill %1

    Sends a termination signal to job 1, using the job number instead of the process ID.

  • disown -h %1

    The shell won't send the job a hangup signal (SIGHUP) when the connection or terminal closes, so it keeps running. We recommend redirecting its output to a file, because after you disconnect there is no terminal to show it.

  • nohup ./backup.sh &

    Runs a command in the background that ignores the hangup signal. When the output isn't redirected to a file, it is saved to nohup.out in the current directory, or to ~/nohup.out when you can't write there.

  • echo $!

    Shows the process ID of the last command started in the background.

xargs and find -exec

  • find /var/www/example -name "*.php" -exec grep -l "eval(" {} +

    Runs a command on the files found. With +, the files are passed in batches to a single command, and with \; the command runs separately for each file, which is slower.

  • find /var/log/example -name "*.log" -mtime +30 -print0 | xargs -0 -r ls -lh

    Lists files that haven't been modified for more than 30 days. Combining -print0 with xargs -0 handles names with spaces correctly, and the -r option prevents a run when nothing is found. After checking the list, you can replace ls -lh with rm. Caution: the deletion is permanent.

  • xargs -I {} dig +short {} < domains.txt

    Runs a command for each line in the file, with {} replaced by the content of the line.

  • find /var/backups/old -name "*.sql" -print0 | xargs -0 -n 1 -P 4 gzip

    Compresses up to 4 files in parallel: -n 1 passes one file to each run, and -P 4 sets how many run at the same time. Caution: gzip replaces each file with a compressed version with the .gz extension.

Before a command that deletes or overwrites files

A pattern such as *.tmp or an empty variable can expand a command far beyond what you intended. Before running rm with a pattern, run the same command with echo in front of it and check the full list of files. In a script that deletes based on a variable, the form rm -rf "${DIR:?}"/* stops the script when the variable is empty or unset, instead of deleting the contents of the root directory.

Alias, function, or script

An alias suits a shortcut for a fixed command, and a function suits cases where you need to pass arguments or run several commands in a row. Write a long task, or a task that runs from cron, as a script: a non-interactive shell doesn't read ~/.bashrc and doesn't expand aliases, so the aliases and functions defined there aren't available in it.

Did you know?

On a Linux VPS, you connect over SSH with full root access and work in Bash with every shortcut, command, and script on this page.

Linux VPS plans

Bash cheat sheet FAQ

What is the difference between ~/.bashrc and ~/.bash_profile?

Bash reads ~/.bash_profile in a login shell, for example when you connect to a server over SSH, and ~/.bashrc in every other interactive shell, for example when you run bash or open a new terminal window on the desktop. To make your settings available in both cases, keep aliases and functions in ~/.bashrc and load it from ~/.bash_profile.

How do I find a command I ran before?

The quickest way is Ctrl+R: type part of the command, and the shell shows the most recent command that matches it. Press Ctrl+R again to move to an earlier match, and Enter to run the command. You can also search the full list with history | grep and run a command by its number, for example !120.

How do I keep a command running after I disconnect from SSH?

Start the command with nohup and an & at the end, and redirect its output to a file. For a command that is already running, pause it with Ctrl+Z, resume it in the background with bg, and run disown -h %1 so the shell doesn't send it a hangup signal when the connection closes. For a long job that you want to come back to and see on screen, screen or tmux is more convenient.

What is the difference between single and double quotes in Bash?

Inside double quotes, variables and command substitution such as $(date) are replaced with their values, and spaces don't split the text into separate words. Inside single quotes, every character stays exactly as it is, so they suit fixed text, passwords with special characters, and grep and awk patterns.

What does set -euo pipefail do at the start of a script?

The line turns on three settings: -e stops the script when a command fails, -u stops it when you use a variable that isn't set, and pipefail makes a pipeline return a failure when any command in it fails, not just the last one. In most cases, this keeps the script from continuing after a failed step. The -e option has exceptions, for example in if conditions, so check the critical commands explicitly.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement