tips
52 tips Bash
One command, setting or habit at a time about Bash: what it does, the line to copy and a caveat or two.
Linux and shell 23
-
Explains why `cmd > file 2>&1` and `cmd 2>&1 > file` send errors to different places.
cmd > file 2>&1 -
Loop over all settings like APP_PORT and APP_HOST without naming each one.
APP_HOST=example.com -
Get some elements of an array, like all but the first, without a loop.
a=(a b c d e) -
Tell an unset variable apart from one that is set to an empty string.
[[ -v b ]] && echo set || echo unset # set -
Loop over positions or keys of an array, also after removing elements.
hosts=(web db cache) -
Run jobs in parallel and still check which of them failed.
wait "$db_pid"; db_status=$? -
Count characters or array items without wc or a loop.
key='abc123xyz' -
Pick a setting like prod_url or test_url based on another variable.
prod_url=https://example.com -
Let a user pick an option by number without writing your own menu loop.
select action in start stop status quit; do -
Add to a string or array without repeating the variable name on the right.
s=foo; s+=bar; echo "$s" # foobar -
Get a short, readable timing for any command or block in a script.
time rsync -a /srv/data/ /mnt/backup/data/ -
Search all commands, aliases and functions your bash knows about.
compgen -c | sort -u | grep '^systemd-' -
Get the PID of the current subshell, where $$ still shows the parent.
echo "main: $$ $BASHPID" -
Finds the directory of the running script so it can load files next to it.
source "$script_dir/config.env" -
Checks whether a TCP port accepts connections using only bash, no nc needed.
timeout 3 bash -c '</dev/tcp/192.168.1.x/443' && echo open || echo closed -
Turns a bash variable into upper or lower case without tr or awk.
name=jellyfin -
Stores values under names in a bash script, so you can look them up by key.
declare -A port=( -
Passes an array to a bash function by name, so the function can change the original.
local -n _list=$1 -
Swaps text inside a bash variable, once or everywhere, without calling sed.
f="my holiday photo.jpg" -
Matches a regular expression in bash and gives you the captured parts without sed.
v="sonarr-4.0.10" -
Times a script or one step of it in bash without calling date.
SECONDS=0 -
Takes a fixed part of a string in bash, counting from the start or the end.
f="backup-2026-11-27.tar.gz" -
Sends both normal output and error messages through the pipe, shorter than 2>&1.
make 2>&1 | less
History and debugging 9
-
Lists command patterns that bash never saves in the history, like ls, pwd and exit.
export HISTIGNORE='ls*:pwd:cd*' -
Preview a history expansion before you run it, then press Up to use it.
!rsync:p -
Keep trace lines out of the normal error output of a script.
set -x -
Delete one line, or a range, from your history after typing something secret.
history -d 1042 -
Show which chain of function calls led to an error in a longer script.
die() { echo "error: $*" >&2; stack >&2; exit 1; } -
Prints the type and exact quoted value of a bash variable, array or function.
declare -p apps -
Saves every command from every open terminal to your bash history instead of only the last one.
shopt -s histappend -
Puts the result of !! or !$ on your command line first, so you check it before it runs.
shopt -s histverify -
Shows the date and time next to every command in your bash history.
export HISTTIMEFORMAT='%F %T '
Safe scripts 8
-
Stop a command substitution at the first failing line, like the rest of the script.
set -e -
Expand an array without breaking elements that contain spaces.
files=("my file.txt" notes.md) -
Avoid a counter that silently ends your script on its first increment.
set -e -
Fail early with a clear message when bash is too old for your script.
echo "needs bash 4 or newer, this is $BASH_VERSION" >&2 -
Parses a script and reports syntax errors without executing a single command.
bash -n backup.sh && echo "syntax ok" -
Makes bash print an error and skip the command when a wildcard matches no files.
shopt -s failglob -
Reads the exit code of every command in the last pipeline, not only the final one.
false | true | false -
Keeps the variables of a bash function inside that function, so callers keep their values.
count=10
Shortcuts 6
-
Park a half-written command in history without running it.
#rsync -av --delete /srv/media/ /mnt/backup/media/ -
Replay a few commands in a row from history, one keypress each.
Ctrl-o # runs make, then shows the next history line -
See exactly which files a glob matches, and edit the list, before pressing Enter.
rm old-*.log -
Takes back your last change on the command line, one step per press.
Ctrl-_ # undo the last edit -
Shows on the prompt what a command becomes once bash fills in variables and aliases.
Alt-Ctrl-e # or press Esc, then Ctrl-e -
Opens the command you are typing in your text editor and runs it when you save.
Ctrl-x Ctrl-e
Config and keys 3
-
Type the start of a command, press Up, and get only matching history lines.
"\e[A": history-search-backward -
Runs a command of your choice before each prompt is shown.
PROMPT_COMMAND='history -a' -
Keeps only the last few folders of the current path in your prompt.
PROMPT_DIRTRIM=2
Shell basics 2
-
Know why [[ ]] is safer in bash scripts and when you still need [ ].
v="a b" -
Shows every alias, builtin, function and file behind a command name.
type -a echo
Globbing 1
-
Brace expansion can pad numbers with zeros and skip values with a step.
echo {01..10}
Nothing in this filter yet.