Fundamentals 10 min read

10 Hidden Bash Tricks Every Linux User Should Master

This article explores ten lesser‑known Bash features—including history substitution, pushd/popd directory stacks, shopt versus set options, Here Docs and Here Strings, advanced parameter expansion, default variable values, signal traps, special shell variables, extglob patterns, and associative arrays—providing practical examples and code snippets for each.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
10 Hidden Bash Tricks Every Linux User Should Master

Introduction

I wrote a follow‑up article because the previous one was unexpectedly popular, and I want to share some lesser‑known Bash features that are useful for everyday scripting.

1) History substitution ^x^y^

A quick way to fix a mistyped command by navigating the command history and replacing parts of the previous command.

$ grp somestring somefile
-bash: grp: command not found
$ ^rp^rep^
grep 'somestring' somefile
$

Note the subtle detail when using this technique with other patterns.

2) pushd / popd

Using the directory stack is handy in scripts, especially inside loops. The example shows how to store the original working directory, iterate over sub‑directories, and push/pop directories.

for d1 in $(ls -d */)
do
  original_wd="$(pwd)"
  cd "$d1"
  for d2 in $(ls -d */)
  do
    pushd "$d2"
    # Do something
    popd
  done
  cd "$original_wd"
done

An alternative version rewrites the same logic using only pushd/popd without manual cd.

3) shopt vs set

The shopt builtin lists shell options, while set controls shell behavior. Example output of shopt shows several options and their current state.

$ shopt
cdable_vars    off
cdspell        on
checkhash      off
checkwinsize   on
cmdhist        on
compat31       off
dotglob         off

4) Here Docs and Here Strings

Here Docs let you create a temporary file from inline text until a delimiter word appears on a line by itself.

$ cat > afile << SOMEENDSTRING
here is a doc
it has three lines
SOMEENDSTRING
$ cat afile
here is a doc
it has three lines
SOMEENDSTRING

Here Strings provide a similar mechanism for a single line of input.

$ cat > asd <<< 'This file has one line'

5) String manipulation with parameter expansion

Instead of using sed or awk, Bash can trim prefixes and suffixes directly.

VAR='HEADERMy voice is my passwordFOOTER'
PASS="${VAR#HEADER}"   # removes leading HEADER
PASS="${PASS%FOOTER}"   # removes trailing FOOTER

echo $PASS   # outputs: My voice is my password

The symbols # and % match from the start and end of the string respectively; ## and %% use greedy matching.

6) Variable default values

Use ${var:-default} to supply a fallback when a variable is unset, or ${var:=default} to assign the default value.

#!/bin/bash
FIRST_ARG="${1:-no_first_arg}"
SECOND_ARG="${2:-no_second_arg}"
THIRD_ARG="${3:-no_third_arg}"

echo $FIRST_ARG

echo $SECOND_ARG

echo $THIRD_ARG

7) Traps

Define a cleanup function and register it with trap to run on termination signals.

function cleanup() {
  rm -rf "$BUILD_DIR"
  rm -f "$LOCK_FILE"
  find "$BUILD_DIR_BASE"/* -type d -atime +1 | rm -rf
  echo "cleanup done"
}
trap cleanup TERM INT QUIT

8) Useful shell variables

Examples of built‑in variables:

RANDOM : generates a random integer.

REPLY : holds input when read is used without a variable name.

LINENO and SECONDS : useful for debugging and timing.

TMOUT : sets a timeout for read.

9) Extglobs

Enable extended globbing with shopt -s extglob and use patterns such as +(pattern), *(pattern), ?(pattern), @(pattern), and !(pattern) for advanced matching.

shopt -s extglob
A="12345678901234567890"
B="  $A  "

echo "B      |${B}|"
echo "B#+( ) |${B#+( )}|"
echo "B#?( ) |${B#?( )}|"
echo "B#*( ) |${B#*( )}|"
echo "B##+( )|${B##+( )}|"
echo "B##*( )|${B##*( )}|"
echo "B##?( )|${B##?( )}|"

10) Associative arrays

Available in Bash 4.x+, associative arrays allow string keys.

declare -A MYAA=([one]=1 [two]=2 [three]=3)
MYAA[one]="1"
MYAA[two]="2"

echo ${MYAA[one]}   # prints 1
WANT=two
echo ${MYAA[$WANT]}   # prints 2
Original English article: https://zwischenzugs.com/2018/01/21/ten-more-things-i-wish-id-known-about-bash/ (translated by D)
scriptingbashcommand-linebash-tipsshell-scripting
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.