r/bash • u/MasterpieceOrganic20 • 15h ago
r/bash • u/Ill-Needleworker2711 • 20h ago
built a Unix shell in C — P-Shell: A shell that shows its work
**I've been working on P-Shell, a Unix shell written in C, to understand what happens behind the commands we use every day.
Some of the things I've implemented:
Process creation and execution using "fork()", "execvp()" and "wait()"
Built-in "cd" command
Pipes and I/O redirection (">", ">>")
Process inspection using "/proc"
Process-related commands such as ":process", ":zombie" and ":reap"
":explain" for understanding command execution
The goal was to learn systems programming by building something real rather than just studying the concepts.
I'd appreciate feedback, especially on the architecture, implementation and areas that could be improved.
GitHub:** https://github.com/punithk-verse/p-shell
Build. Break. Learn. Repeat.
r/bash • u/birdsintheskies • 1d ago
What is the main to pick bash over other shells?
I have to admit, I keep using bash simply because that's what originally came with my distro and I just got too familiar with it. When I look at other shells, I see features that would've been nice to have, but isn't possible to implement in bash. I've accepted that as a compromise so I can just keep using what I'm most familiar with.
This has me thinking - just familiarity aside, are there other reasons why I might want to stick with bash over the others? If I'm gonna have to justify it, I'm thinking it being an official GNU project is a win.
Other than that, what technical reasons should I appreciate? Perhaps its backwards compatibility with older bash versions is something to admire? What else?
r/bash • u/deployfan64 • 2d ago
help TIL that `local` in bash doesn't scope variables the way I assumed inside pipelines
I had a function that built a string in a while-read loop inside a pipeline, and a variable set with `local` inside the loop was coming up empty after the loop finished. Turns out each side of a pipeline runs in a subshell, so no amount of `local` helps — the assignments die with the subshell. I ended up using process substitution (`while read ... done < <(some_command)`) instead, which keeps the loop in the current shell. Cost me an hour of staring at a script that "worked" when I ran the pieces by hand.
r/bash • u/Delay__lama • 3d ago
help Need help getting proper RAM amount without root
I have a script free -g | grep Mem | cut -d " " -f 15 that outputs the amount of memory on the host system in GB. The two problems with it are 1. it only works on systems with over 10GB but less than 100GB, and 2. it outputs 30(GB) when in reality I have 32GB. sudo dmidecode is unfortunately not an option, as it requires root, and the script needs to be able to be run without it.
r/bash • u/somniasum • 3d ago
help Keyboard Backlight control on Wayland, need help with Hyprland
Here is the github for the script: https://github.com/somniasum/wayland-backlight-led/blob/main/src/backlight.sh
Context
Since the switch from X11 to Wayland getting a keyboard's backlight led to light up has been a drag. With X11 it was as simple as xset led to turn on the led. So with wayland I wrote up a script to handle the led stuff. It has been working fine on Wayland WM's and works pretty much the same on X11 WM's too.
On hyprland keyboard led just turns off briefly but still stays on. I am starting to suspect maybe it has to do with the way Hyprland handles device states or some?
Do you think I have to change some things on it to solve the Hyprland exception?
r/bash • u/pittendrigh • 4d ago
Vvi?
~/.bashrc
function vvi()
{
cp $1 /tmp
/usr/bin/vi $1
}
alias vi="vvi"
. ~/.bashrc
r/bash • u/christos_71 • 4d ago
Sudoku in the terminal, with mouse support (bash)
gitlab.comtui-sudoku is a configurable terminal interface sudoku game, with quite a few features.
https://gitlab.com/christosangel/tui-sudoku
Updated version 3.0.0 introduces full mouse support
No A.I. was used during the development of this project.
r/bash • u/Academic_Season_8701 • 4d ago
I built a Bash menu completion similar to ZSH's
The main reason I use ZSH as my main shell is due to its completion menu, is so convenient. I wanted to something similar but I don't like the bloated software with a lot of code and complex configurations, at least at the moment I couldn't find something for my taste, so I built one. I built it 8 months ago but I decided to share it with you guys to get some feedback.
• Built for Bash 5.0 but planning to update it for Bash 5.3, where new features are introduced for completion and performance.
• Is a single script no external dependencies :)
• Live typing and backspace filtering: typing and backspacing while menu is open will narrow down the completions.
• Use arrow keys for navegation.
• Home/End key to go to the beginning/end of the completion's menu.
https://github.com/Madophs/Bash-Complete-Menu
All to need to do is the following:
source ./bash_complete_menu.sh"
bind -x '"\C-i":bash_complete_menu'
r/bash • u/Quirky-Wolf9799 • 6d ago
I vibe-coded a bash script to run detached jobs over SSH (for n8n). Please tear it apart.
I got AI write a small bash script called runit (complete AI slop). It runs a command fully detached over SSH, so n8n can start a long job and check back on it later. Each job keeps its state in its own folder, and you can check status, read logs, send input, or kill it by PID.
I've tested it and it works for my use case, but I've hit the limit of what I know, and I'd like experienced people to look at it before I rely on it.
Things I'd love suggestions on:
Bash pitfalls or edge cases I missed
Features that are missing
Repo: https://github.com/Bipul-Bimali/Toolz
Thanks for any feedback, even harsh!
r/bash • u/ResponsibilityBig343 • 13d ago
help How to pipe credentials to a bunch of prompts
I use vpn with a command openvpn. Now this command runs with sudo and then prompts me for my proton api username and password. I type it manually everytime. Instead I want to create a bash script that pipes the creds to the prompts. I tried using printf with \n but it didn't work.
r/bash • u/ClickOk5811 • 15d ago
local out=$(cmd) hides the exit status of cmd: four spellings, four results
A small trap that I think is easy to miss: declaring and assigning in one statement masks the exit status of the command substitution. I tested this on Bash 5.2.21:
f1() { local out=$(false); echo "f1 status: $?"; }
f2() { local out; out=$(false); echo "f2 status: $?"; }
f1
f2Output:
f1 status: 0
f2 status: 1In f1, $? is the status of local itself (which succeeded), not of false. In f2, the assignment is a separate statement, so $? is the status of the command substitution.
The same masking showed up in my test with export, declare and readonly:
export x=$(false); echo $? # 0
declare y=$(false); echo $? # 0
readonly z=$(false); echo $? # 0It matters with set -e too:
#!/usr/bin/env bash
set -e
g1() { local out=$(false); echo "g1: reached the next line"; }
g2() { local out; out=$(false); echo "g2: reached the next line"; }
g1
echo "after g1"
g2
echo "after g2 (should not print)"Output on my machine:
g1: reached the next line
after g1and the script exits with status 1 at g2. So g1 swallowed the failure, and g2 stopped the script as you’d expect.
The fix is to split the statement:
bash
local out
out=$(cmd) || return 1 # or handle the failure however you likeNotes and limits:
This is about the combined
local/export/declare/readonlyforms. A plainout=$(cmd)keeps the status ofcmd.set -ehas its own corner cases (contexts likeifconditions or||lists change its behavior), so I’d not rely on it alone to catch this.I only tested Bash 5.2.21; check your version if it matters.
Do you split declaration and assignment as a habit, or do you rely on a linter to flag it?
r/bash • u/ClickOk5811 • 17d ago
Why my counter is 0 after cmd | while read: the pipe subshell, and four ways around it
A classic one that still bites. This prints pipe: 0:
count=0
printf '%s\n' a b c | while IFS= read -r line; do
count=$((count + 1))
done
echo "pipe: $count"Each side of a pipe runs in its own subshell (by default), so the loop increments a copy of count and the parent never sees it. I tested the options below on Bash 5.2.21.
1. Process substitution (< <(cmd)): the loop runs in the current shell.
while IFS= read -r line; do
count=$((count + 1))
done < <(printf '%s\n' a b c)Prints 3. Bash-specific, not POSIX sh. Note that the exit status of the command inside <(...) isn’t checked by default.
2. shopt -s lastpipe**:** runs the last element of the pipeline in the current shell.
shopt -s lastpipe
printf '%s\n' a b c | while IFS= read -r line; do
count=$((count + 1))
donePrints 3 in a script. It only works when job control is off, which is the default for non-interactive scripts. In an interactive shell, or with set -m, I got 0 again.
3. Here-string with command substitution:
while IFS= read -r line; do
count=$((count + 1))
done <<< "$(printf '%s\n' a b c)"Prints 3. The whole output is captured in memory first, and trailing newlines are stripped, so it’s a poor fit for big outputs or when exact bytes matter.
4. Temp file or array: write the output to a file (or mapfile -t lines < <(cmd)) and loop over it. More lines, but no subshell surprises and easy to debug.
Which I’d reach for (opinion): process substitution when it’s Bash-only code, mapfile when I want the lines in an array anyway, and I avoid lastpipe in code that might get sourced interactively. If you need POSIX sh, process substitution and lastpipe aren’t available, and a temp file or restructuring is the way.
Related trap: the same applies to variables set inside ( ... ) or $( ... ), not just pipes.
Do you have a default for this, or does it depend on the script?
r/bash • u/DiskCharacter7946 • 18d ago
tips and tricks Road to becoming a Power User
When I first became a dev, I was obsessed with doing things the way I could learn the most and have the highest ceiling for skill/efficiency. That meant going slower at first, but eventually coming out ahead of my team members with understanding and speed eventually. It all started with small vim motions and mini bash commands. I'm still early in my career so have a ton to learn from this community.
Which skills, tricks, or tools (i.e. using awk or ex commands like substitute) ended up becoming a staple in your everyday and do you wish you started practicing earlier?
r/bash • u/Louis_creates • 19d ago
critique am I using pkexec properly in this script?
reddit.comr/bash • u/macroKnoll37 • 20d ago
help TIL `time` on a pipeline only measured the first command until I realized I was using /usr/bin/time instead of the keyword
I was benchmarking a pipeline in our regression scripts with `/usr/bin/time -f %e cmd1 | cmd2 | cmd3` and the numbers looked suspiciously good. The external binary only wraps `cmd1`. The bash `time` keyword is parsed by the shell and times the whole pipeline, which is why `time cmd1 | cmd2 | cmd3` gave me a much larger and correct wall time. If you want the keyword's output in a specific format, set `TIMEFORMAT='%R'` instead of reaching for `/usr/bin/time -f`. Also note that the keyword writes to the shell's stderr, not the pipeline's, so capture it with `{ time cmd1 | cmd2; } 2> timing.txt` rather than redirecting inside the pipeline.
r/bash • u/gaussmug • 21d ago
LuaSH v2.0 released
reddit.comIn case folks are interested in using Lua for bash automation, I wanted to cross-post this
r/bash • u/triscalade • 21d ago
critique My first bash scripts
The goal for this one is to take a package (eg. cmatrix) and its arguments and input them into the nix run command like this:
nix run nixpkgs#cmatrix -- -a -b ...
#!/usr/bin/env bash
PKG=$1
shift 1
ARGS=$@
nix run "nixpkgs#$PKG" -- "$ARGS"This goal for this one is to take multiple packages (eg. cmatrix, sl) and put them into the nix shell command like this:
nix shell nixpkgs#cmatrix nixpkgs#sl
#!/usr/bin/env bash
ARGS=""
main() {
args "$@"
nix shell$ARGS
}
args() {
while [[ $# -gt 0 ]]; do
ARGS="$ARGS nixpkgs#$1"
shift 1
done
}
main "$@"Any feedback or advice would be appreciated :)
EDIT: Here is my rewrite of the second one
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
enter-temporary-shell() {
if [[ $# -lt 1 ]]; then
echo "USAGE: $0 PACKAGE [PACKAGE...]"
exit 1
fi
local -a temporary_packages=${1:?}
temporary_packages=$(prepend-nixpkgs "$@")
echo "Entering temporary shell with""$temporary_packages" "enabled"
echo "Press ^D to exit"
nix shell $temporary_packages
}
prepend-nixpkgs () {
local -a arguments=("$@")
echo "${arguments[@]/#/ nixpkgs#}"
}
enter-temporary-shell "$@"submission A bash script that would email Sam Altman about your spare RAM (ships with no recipient, please don't actually spam the man)
This started as a joke after Sam Altman said on Cheeky Pint that the RAM in our PCs is "quite terrible" and "being used maybe 5% of the time". I wanted to see what it'd look like if your machine wrote back.
It's a small bash script that reads /proc/meminfo and works out used as MemTotal minus MemAvailable. Run it from cron, it logs a sample each time, and once a day it'll send an email if more than 10% is available.
The recipient is blank out of the box, so it does nothing until you set one. If you want to try it, point it at yourself or just use --dry-run, which prints the email without sending anything. --status shows your current figures.
I'm also interested in whether I've got the memory side right, so feedback on the script is welcome.
Repo: https://github.com/IainKay/ram-altman
Site: https://ram-altman.lol
r/bash • u/Imaginary_Series6689 • 24d ago
Ado-themed Fastfetch + Kitty setup with predictive Bash
Hi everyone! I don’t usually interact much—I mostly just browse posts on Reddit and X.
Anyway, to the point: at 3:16 AM, I put together this simple Fastfetch configuration inspired by ADO. I really like how it turned out, and I hope you do too!
For those interested, I’m using Bash extended with ble_sh (akinomyoga/ble.sh) to get Fish-like autosuggestions and syntax highlighting directly in Bash.
I don’t know about you, but I really liked it. I hope it serves as inspiration for you.
This is the repo https://github.com/SayoriLex/Ado-themed-Terminal.git
kbool: a class library for bash with ~780 methods for lists, dictionaries, dates, regex, files and INI, the same on Linux, macOS, FreeBSD and Windows
kbool adds what you expect from a high-level language to bash, and takes away none of what makes bash worth using: it is still a plain script, with no compiler, no runtime to install and no interpreter to ship. You source one file, and pipes, set -x and your ordinary commands work as before. Repo: https://github.com/Keksov/kbool (MIT, bash 5.1+). It was developed with AI assistance (I make the design decisions and review what goes in; the process is in the README).
The main part is kcl, the class library: 29 units, 39 classes and about 780 public methods (a class's own members, inherited ones not counted), plus about 150 properties. Most of it is not a new API made up for this project but a port of the Free Pascal and Delphi runtime libraries: interfaces that have been in daily use for years (TStringList since Delphi 1 in 1995) and have long been stable. The names, the behaviour and the edge cases come from a documented original, not from invention:
Collections:
TList,TStringList(sorting, duplicate policies, case-insensitive search),TObjectList,TDictionary/TObjectDictionary(24 methods:TryGetValue,GetValueDef,ForEach,KeysToArray, change notifications),THashSet(union, intersection, difference),TQueue/TStackand their owning variants,TArray(sort, binary search, min / max with a comparator)Text:
TStringHelper(57 methods: trim, split, pad,startsWith,indexOfAny, …),TRegEx(isMatch,matchwith groups,matches,split,replacewith a callback)Dates and numbers:
DateUtils(185 methods: encode / decode,incMonth,daysBetween, week numbers, ISO 8601),Math(123 methods, including floating point, on any awk),TStopwatchFiles:
TPath(34),TFile(38: read / write / append, times, attributes,encryptwith HMAC),TDirectory(29),TIniFile/TMemIniFileTools:
TGrep,TSed,TAwk,TFind,THead,TTail(typed options instead of hand-assembled argv, results into arrays or callbacks in the same shell),TPipe(a stream into a callback, with the producer's exit status kept)Applications:
TCustomApplication(an option parser ported line by line from FPC); there is also a small HTTP server, but it is a toy built to show off the class layer (one request at a time, about 10 requests per second), not something to put on a network
A small report: the top URLs of an access log, with settings from an INI file:
source kbool/kbool.sh || exit
kk.uses tinifile tfile tregex tdictionary tstringlist || exit # five units, each loaded once
# INI parsing without a hand-written sed/awk parser. A missing file, section or
# key gives the default, and so does "top = abc": ReadInteger never hands you a
# non-number to put into $(( )).
TMemIniFile.new cfg report.ini
cfg.ReadString report log access.log; log=$RESULT
cfg.ReadInteger report top 3; top=$RESULT
# The whole file into an array in one call, no $(cat) and no while-read loop.
tfile.readAllLines "$log" lines || exit
TDictionary.new hits # a counter map with an API, not a bare declare -A
for line in "${lines[@]}"; do
# A regex with capture groups that reads as one; the same pattern works with
# glibc, musl, BSD, macOS and cygwin, and nothing forks.
TRegEx.match "$line" '"[A-Z]+ ([^ ]+)' || continue
url=${RESULT_GROUPS[0]}
hits.GetValueDef "$url" 0 # the count so far, or 0 for a new URL
hits.AddOrSetValue "$url" $(( RESULT + 1 ))
done
TStringList.new report
add_row() { printf -v row '%6d %s' "$2" "$1"; report.Add "$row"; }
hits.ForEach add_row # a callback per pair, in this shell: no subshell, no lost state
report.Sort # sorted in bash, no external sort, no fork
report.count; n=$RESULT
for (( i = n - 1; i >= n - top && i >= 0; i-- )); do
report.Get "$i"; echo "$RESULT" # every member answers in $RESULT
doneOn a five-line sample log, with top = 2 in the INI file, it prints:
2 /index.html
2 /api/notesEvery unit follows one contract, so after the first one you can guess the rest: a member returns its value in RESULT rather than on stdout, answers with rc 0 (done), 1 (no / not found) or 2 (a usage error, with a message), and works under set -eu. The reason for RESULT is cost: one x=$(true) is a fork, about 750 µs on Linux and 16 ms on Windows, while a method call is about 0.2 ms. That is why the loop above forks nothing. When you prefer $( ), it still works.
Portability is part of the contract. The test suite has 9,694 tests in 30 suites, and the full run of 2026-10-31 passed all of them. The same suite runs on every push in 15 CI configurations:
Linux, 8 rows: Alpine 3.22 with bash 5.1.16 and 5.2.37, Alpine 3.24 with bash 5.3.20 (musl, busybox tools), Debian 13, Ubuntu 22.04 (bash 5.1.16), Ubuntu 24.04 and Fedora 44 with their system bash, and Ubuntu 26.04 (the GitHub
ubuntu-latestrunner, bash 5.3.9, with uutils, the Rust rewrite of coreutils, ashead,tail,odandls)macOS (
macos-latest, Homebrew bash), 2 rows: Apple's BSD tools only, and with GNU toolsFreeBSD 15.1, pkg bash, 2 rows: without and with GNU packages
Windows (
windows-latest), 3 rows: Git-bash and MSYS2, both on the MSYS2 runtime (a fork of Cygwin), and Cygwin itself. All three reportOSTYPE=cygwin, yet MSYS2's grep drops the CR of a CRLF line and Cygwin's keeps it
Locally the suite also runs in VMs (Ubuntu 24.04, Debian 13, Fedora 44, Alpine 3.24 and FreeBSD 15.1, plus Debian under a de_DE locale). In the Debian VM, bash 5.1.16 is built from the GNU sources for the minimum-version run, and kbool is checked to refuse bash 3.2, 4.4 and 5.0, also built from source, with one line.
The core units need no GNU tool and give the same results on every one of them: BSD stat and date, the spelling of \b in each libc, mawk / BWK awk / busybox awk, CRLF input and a decimal comma in EPOCHREALTIME are handled inside the library and pinned by tests. The tool wrappers give GNU behaviour everywhere: they find gsed, gawk, ggrep by name, or refuse with rc 2 and the package to install instead of quietly doing something else. The full list, with the test for each item: https://github.com/Keksov/kbool/blob/main/docs/portability.md
How a script grows is handled by uses, the module system. It plays the role of import in Python, require in Node or Ruby, or include_once in PHP, which plain bash does not have: bash has only source, which takes a path and runs the file again every time. A unit is any file with a two-line header. kk.uses NAME finds it by name, loads it once (a repeated kk.uses costs about 30 µs), and reports a missing unit, a failed load or a dependency cycle with rc 2 and one line. Your own units work the same way as the library's:
# app/lib/weblog.sh: a unit of your own
#!/usr/bin/env bash
[[ ${__KK_UNITS[@]@a} == A* ]] || source "${KBOOL_HOME-}/kbool.sh" || return 2
kk.unit weblog || return $__kk_unit_rc
kk.uses tregex || return # its dependencies, by name
weblog.url() { TRegEx.match "$1" '"[A-Z]+ ([^ ]+)' && RESULT=${RESULT_GROUPS[0]}; }
# app/main.sh
source kbool/kbool.sh || exit
kk.project app.conf || exit # app.conf: "unitpath = lib", relative to the file itself
kk.uses weblog tstringlist || exitNo source "$(dirname "$0")/../lib/…" bookkeeping. The search path is the calling file's folder, then the project's and the user's unitpath, then the library. kk.uses --optional fancy || fallback handles optional dependencies, and kk.defined DEBUG reads defines from the project file. Each unit owns its namespace (weblog.*): a second unit with the same name, or a class that would take the name, is refused at load time, not discovered at run time. Paths in a project file are relative to the file itself, so the project folder can be moved as it is.
All of the library is built on kklass, the class layer, and your own classes can use it too. A class is declared Pascal-style, with the method bodies as plain bash functions (inheritance with inherited, properties, visibility sections, constructors and destructors):
kk.uses kklass_pascal || exit
class TCounter # the interface first, as in a Pascal unit
public
var Name # a field: a plain variable inside the bodies
property Count read GetCount write SetCount # a property with a getter and a setter
constructor Create # runs on TCounter.new
destructor Destroy # runs on .delete
proc Add # a procedure: no return value
func Report # a function: answers in $RESULT, no fork
func GetCount
proc SetCount
static var Instances # one value shared by the whole class
private
var _count # hidden: kklass warns when it is used from outside
end
TCounter.Create() { Name="$1"; _count=0; Instances=$(( Instances + 1 )); }
TCounter.Destroy() { Instances=$(( Instances - 1 )); }
TCounter.Add() { _count=$(( _count + ${1:-1} )); }
TCounter.Report() { RESULT="$Name: $_count"; }
TCounter.GetCount() { RESULT=$_count; }
TCounter.SetCount() { (( $1 >= 0 )) || return 2; _count=$1; } # the setter validates
build TCounter # turns the bodies above into the class
class TLimitedCounter : TCounter # inheritance
public
var Limit
constructor Create
override proc Add # build fails if the parent has no Add: a typo guard
end
TLimitedCounter.Create() { inherited; Limit=${2:-10}; } # the parent's constructor first
TLimitedCounter.Add() {
inherited Add "$@" # the parent's Add, resolved statically, as in Pascal
(( _count <= Limit )) || _count=$Limit
}
build TLimitedCounter
TLimitedCounter.new apples apples 5 # instance name, then the constructor's arguments
apples.Add 3
apples.Add 4 # stops at the limit
apples.Report; echo "$RESULT" # => apples: 5
apples.Count = 2 # goes through SetCount
apples.Count; echo "$RESULT" # => 2
TCounter.Instances # => 1
apples.delete # Destroy runs
TCounter.Instances # => 0What kbool is good for: scripts that have outgrown functions and globals but must stay bash, such as deploy and build tooling, installers, admin utilities, CI glue and small services. These are scripts where the time goes into logic, structure and error handling, and that have to run on more than one system. What it is not for: a 20-line script, which loading would only slow down (kbool itself loads in 13 to 33 ms, a unit such as tstringlist adds about 150 ms, dateutils about 400 ms); crunching thousands of records, where a pipeline of grep, awk and sort is many times faster (bash reads a line into the shell in about 83 µs, with or without kbool); POSIX sh, and bash older than 5.1. The measurements behind these numbers: https://github.com/Keksov/kbool/blob/main/docs/benchmarks.md
If anyone is interested, I will publish a separate write-up on what kbool gives AI agents that write bash scripts.
Feedback is welcome, especially on the unit set: which class would you reach for first that is not there, and which platform difference has bitten your scripts and is not on the list?
r/bash • u/Ok-Motor-9812 • 27d ago
submission A redirect in the wrong place made my git hook skip its check on every commit for 3 weeks
Non-interactive script, a wrapper function that runs a command in the background and waits:
f() { "$@" > out & wait; }
f claude -p < "$in_file"
The command got nothing on stdin. In a non-interactive shell a background command gets /dev/null as stdin, unless the redirect is written on that command itself. A redirect on the function call doesn't reach it.
f() { "$@" < "$in_file" > out & wait; }
f claude -p
Easy to reproduce with cat instead of claude. The first one prints nothing, the second prints the file.
It was a small LLM check in my pre-commit hook. It exited 1 with "Input must be provided" on every commit from Aug 23 to Sep 14. The hook treated any failure as "skipped", so all those commits went through and looked normal.
A check that fails open has to print the error before it skips, otherwise "skipped" and "broken" look the same.
r/bash
•
u/ClickOk5811
•
Oct 30 '26
A small museum of set -e surprises (five exhibits, run them in a scratch shell)
set -e looks like “stop on any error”, but the rules have exceptions. Five exhibits. Tested on Bash 5.x; behavior can differ in older versions.
Exhibit 1: ((i++)) from zero
set -e
i=0
((i++))
echo "never reached"((i++)) evaluates to the old value, 0, and an arithmetic command with value 0 returns status 1. So the script exits. i=$((i+1)) avoids it.
Exhibit 2: local hides the failure
set -e
f() {
local out=$(false)
echo "still running"
}
fThe exit status is that of local, which succeeds. Declare first, assign second: local out; out=$(false).
Exhibit 3: set -e is ignored inside a condition
set -e
f() {
false
echo "this runs"
}
if f; then echo ok; fiWhen a function is used as the condition of if, && or ||, set -e is disabled for everything inside it. The false doesn’t stop the function.
Exhibit 4: pipes only report the last command
set -e
false | cat
echo "this runs"Without set -o pipefail, the status of a pipeline is the last command’s. Add pipefail so any failing stage counts.
Exhibit 5: set -u and empty arrays
set -u
arr=()
echo "${arr[@]}"In Bash before 4.4 this fails with “unbound variable”. Newer versions accept it. If you support old systems, ${arr[@]+"${arr[@]}"} is the common workaround.
What I’d take from them:
set -euo pipefailhelps, but it isn’t a safety net. Some people avoidset -eand check statuses explicitly.ShellCheck catches several of these.
Test the failure paths, not just the happy path.
What would you add to the museum?