keepcalculator

06 Numbers and Powers

Bash Tips and Tricks: 20+ Commands

Card No. 06·54689 · Updated · Standard formula, shown below

This article answers the question “Bash tips and tricks?” by giving you a practical set of commands, shortcuts, and scripting patterns that save time and prevent errors. You’ll learn how to move faster on the command line, write safer scripts, and avoid common pitfalls—whether you’re a beginner or have used Bash for years.

Why Bash Skills Matter

Bash (Bourne Again SHell) is the default shell on most Linux distributions and macOS, and it’s available on Windows through WSL or Git Bash. It’s the glue that connects commands, files, and programs, so knowing a few solid tricks can turn a tedious manual task into a one-liner. More importantly, Bash scripts are how system administrators, developers, and data scientists automate repetitive work—from renaming hundreds of files to deploying software. Even a small set of well-chosen tricks can make your daily terminal use noticeably faster and less error-prone.

Command-Line Navigation and Editing

These are the keystrokes you’ll use constantly. They work in the default Bash mode (emacs-style) and are worth memorizing.

  • Ctrl+A / Ctrl+E – jump to the beginning or end of the line.
  • Ctrl+U / Ctrl+K – delete from the cursor to the start or end of the line.
  • Ctrl+W – delete the word before the cursor.
  • Ctrl+R – reverse search through your history. Type part of a command and press Ctrl+R repeatedly to cycle through matches.
  • !! – repeat the last command. Useful after a permission error: type sudo !! to rerun it with sudo.
  • !$ – expands to the last argument of the previous command. For example, after mkdir myproject, type cd !$ to go into it.

One often-overlooked trick is set -o vi, which gives you vi-style editing on the command line. If you’re already comfortable with vi, this can be a huge productivity boost.

History and Reuse

Your command history is a goldmine. Here’s how to use it effectively.

  • Ctrl+R – as mentioned, interactive reverse search.
  • history – shows the list of past commands with numbers.
  • !number – execute command number from history.
  • !string – execute the most recent command that starts with “string”.
  • fc – open the last command in your default editor, modify it, and run it when you save and exit.

To avoid losing history when you close multiple terminals, add these lines to your ~/.bashrc:

shopt -s histappend
PROMPT_COMMAND="history -a; $PROMPT_COMMAND"

This appends each command to the history file immediately, instead of waiting for the shell to exit.

File and Directory Operations

These tricks go beyond the basics of ls and cd.

  • cd – – go back to the previous directory. It’s like an “undo” for directories.
  • pushd / popd – maintain a stack of directories. pushd /tmp switches to /tmp and remembers where you were; popd returns.
  • ls -la – shows all files, including hidden ones, with details. Add --color=auto to colorize output.
  • find . -name “*.txt” – find files by name. Use -iname for case-insensitive.
  • grep -r “pattern” . – search recursively in files. Add -l to list only filenames.

A powerful one-liner to delete all files older than 30 days in a directory:

find /path/to/dir -type f -mtime +30 -delete

Be careful with -delete—test with -print first.

Pipelines and Redirection

Pipelines are the heart of Unix philosophy. Here are some patterns that come up again and again.

  • command1 | command2 – send the output of command1 to command2.
  • tee – write to a file and also display on screen: command | tee output.log
  • 2>&1 – redirect stderr to stdout. Example: command > file 2>&1 captures both.
  • > /dev/null – discard output. Useful when you only care about the exit status.
  • |& – shorthand for 2>&1 | in Bash.

Example: count the number of files in the current directory (excluding subdirectories):

ls -la | grep "^-" | wc -l

Or, more robustly, using find:

find . -maxdepth 1 -type f | wc -l

Variables and Expansion

Understanding how Bash expands words can prevent many headaches.

  • ${var:-default} – use default if var is unset or empty.
  • ${var:=default} – assign default if var is unset or empty.
  • ${var:?error message} – if var is unset, print error and exit.
  • ${var%pattern} – remove shortest match of pattern from the end.
  • ${var#pattern} – remove shortest match from the beginning.

For example, to get the filename without its extension:

file="archive.tar.gz"
echo "${file%.*}"   # outputs archive.tar
echo "${file%%.*}"  # outputs archive (greedy)

To convert a string to uppercase:

echo "${var^^}"

And to lowercase:

echo "${var,,}"

Scripting Best Practices

When writing a Bash script, these habits will save you from debugging nightmares.

  1. Start with a shebang: #!/usr/bin/env bash – ensures the script runs with the user’s bash.
  2. Use set -euo pipefail – exit on error, undefined variable, and pipeline failure. This catches many silent bugs.
  3. Quote your variables: always use "$var" to prevent word splitting and globbing.
  4. Use functions for reusable blocks, and define them before calling them.
  5. Check exit status: if command; then ... fi is cleaner than if [ $? -eq 0 ].
  6. Use local inside functions to avoid polluting global variables.

Example of a safe script skeleton:

#!/usr/bin/env bash
set -euo pipefail

main() {
    local input="${1:-}"
    if [[ -z "$input" ]]; then
        echo "Usage: $0 <input>" >&2
        exit 1
    fi
    echo "Processing: $input"
}

main "$@"

Common Pitfalls and Misconceptions

Even experienced users trip on these. Let’s clear them up.

  • Spaces in assignments: var = 5 is wrong; it must be var=5 (no spaces).
  • Using [[ ]] instead of [ ]: the double bracket is a Bash built-in that handles empty variables and regex better. Always prefer [[ ]] in Bash.
  • Forgetting to quote in [[ ]]: actually, inside [[ ]] you don’t need to quote variables, but it’s still safe to do so.
  • Using cat file | grep pattern: this is a useless use of cat; use grep pattern file.
  • Not handling filenames with spaces: always quote, or use find -exec with +.

Frequently Asked Questions

What is the difference between sh and bash?

sh is the POSIX shell standard; on many systems it’s actually a symlink to bash running in POSIX mode. Bash has extra features like arrays, [[ ]], and ${var^^} that are not in POSIX. If your script uses Bash-only features, use #!/usr/bin/env bash; if it’s meant to be portable, stick to POSIX syntax.

How do I debug a Bash script?

Run it with bash -x script.sh to trace each command. You can also add set -x inside the script to turn on tracing, and set +x to turn it off. Use PS4 to customize the trace prompt, e.g., PS4='+ $LINENO: ' to show line numbers.

Why does my script fail when the path has spaces?

Because you didn’t quote the variable. Always use "$var" unless you explicitly want word splitting. For example, cp $file /dest breaks if $file contains spaces; cp "$file" /dest works.

How can I make a command run in the background and ignore its output?

Use command > /dev/null 2>&1 &. The > /dev/null discards stdout, 2>&1 sends stderr to the same place, and & puts the job in the background. To manage it later, use jobs, fg, and bg.

What’s the best way to read a file line by line?

Use while IFS= read -r line; do ...; done < file. The -r prevents backslash escapes, and IFS= preserves leading/trailing whitespace. Avoid for line in $(cat file) because it splits on whitespace and globs.

How do I get the exit code of the last command?

Use the special variable $?, but note that it’s overwritten by every command, including echo. So capture it immediately: cmd; status=$?; echo "Exit: $status".

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →