Pipes, Redirection and Exit Codes: Shell Scripting, the Next Step
6 files, 24 lines, 4 TODO lines; false | true gives PIPESTATUS 1 and 0, pipefail on exits 1, off exits 0; a spaced filename splits into 2 words unquoted, 1 quoted; backup 6 files, 445 bytes. Bash 5.2.21, measured.

One thing first, so you do not read this twice: the site already has a Bash guide from scratch, "Bash Scripting from Zero", published 23 November 2026, covering variables, single and double quotes, conditionals, for and while loops, and functions, ending in a small script that tidies files. That one is "from zero"; this one is "what comes next". It does not re-teach those five topics. It covers the half that guide did not cover, or only mentioned in passing: pipes, redirection, and exit codes. Those three are where shell scripting differs most from languages like Python or Node.js, and they are what turn everyday repeated steps into one automatic pipeline. The split is simple: to learn variables and loops, read that guide first; to make a chain of commands work together and to know where it went wrong, read this one.
The example here is a fictional notes folder for "Xiaoman Studio": 6 files, 24 lines, 4 lines carrying TODO. It is not a real record. Every step was really run, though: the demo script is demo252_g1.sh, the local environment is GNU Bash 5.2.21, and the Chinese and English runs share the same logic, so their numbers are identical; both transcripts are kept in this directory. The headline numbers first: the inbox holds 6 files, the 4 .txt files have 14 lines between them, and TODO appears on 4 lines; the pipeline false | true leaves exit codes 1 and 0, and with pipefail on the whole pipeline exits 1, with it off the pipeline exits 0; a filename with a space in it splits into 2 words unquoted and stays 1 word quoted; 5 file checks all said yes; the backup copied 6 files, 445 bytes in total, and after renaming one file there are still 6 files, 1 of them a .bak. Keep those numbers in mind; everything below is them unpacked.
Check the environment first: which shell is this, and which version
Before starting, look at what you are using. The first step of the demo does only two things: it prints the Bash version, 5.2.21, and it runs a command that always succeeds, true, and checks that its exit code is 0. The version number looks dull, but it is the premise for everything that follows: different Bash versions support different syntax, and when you report a problem or look something up, the version is the first thing to say. The demo also starts with set -uo pipefail, three seatbelts for the whole script, which section 4 takes apart one by one. Remember what it looks like for now; do not rush to memorise what it means.
One more thing to say up front: the first line #!/usr/bin/env bash and giving the file execute permission with chmod +x are covered in detail in the from-zero guide, so they are not repeated here. This guide assumes you can already create a .sh file, make it executable, and run it with bash demo252_g1.sh. If you have never got any script running, go back and get the first step of that guide working, then come back here. Keep the order.
Pipes: let commands pass the work along
A pipe is the vertical bar |. It means: take the output of the command on the left and feed it straight in as the input of the command on the right. The second step of the demo uses just two pipes to size up a whole folder. The first is cat inbox/*.txt | wc -l: the left side pours out the contents of all 4 .txt files, the right side, wc -l, counts lines, and the answer is 14 lines. The second is grep -r TODO inbox | wc -l: the left side, grep -r, finds every line carrying TODO in the whole inbox, the right side counts them, and the answer is 4 lines. One more line without a pipe in it: ls inbox | wc -l says the inbox holds 6 files.
The point of a pipe is not "fewer keystrokes". It is "each command does one job". cat only pours out content, grep only picks lines, wc only counts; none of them knows the others exist, and the pipe joins them up. To ask a different question, swap one section of pipe: change TODO to another word and you count that word instead; change wc -l to sort | uniq -c and you count how many times each case appears, without touching the earlier commands. When writing a script, first work out "where does the data come from, which stations does it pass through, what does it become at the end", then join the pipes one section at a time. That is far easier to change later than one big command that does everything.
One detail worth pausing on: data in a pipe flows through; it is not saved to a file first and then handed to the next command. As the left side produces each line, the right side processes it. With 6 files and 24 lines you cannot see the difference, but with a large file, or a command that keeps producing output, it matters: a pipe processes as it goes, without first piling the whole result into memory. The other side of that coin is that if any section in the middle fails, what comes out the far end is incomplete data, and the next section will still happily count out a number that looks plausible. That is why the exit code of a pipeline needs its own look, which is what section 4 is about.
Redirection: where output goes, and where errors go
Every command has two ways out: normal results go to standard output, and error messages go to standard error. They are two separate pipes that both happen to flow onto your screen, so they look like one thing. They are not. Redirection re-routes those two pipes. The third step of the demo re-routes four times. First, ls inbox/nope.txt 2> errors.txt: that file does not exist, so the error from ls is caught by 2> and written into errors.txt, which measures 1 line. Without 2>, that error would print straight to the screen, mixed in with normal output. Second, echo "first line" > out.txt: > creates the file or empties it and writes, leaving out.txt at 1 line. Third, echo "second line" >> out.txt: >> appends without emptying, leaving out.txt at 2 lines. Fourth, wc -w <<< "one two three": <<< is a here-string, feeding a short piece of text straight in as a command's input, and it counts 3 words.
Of those four re-routings, the easiest to get wrong is > versus >>. One extra angle bracket flips the meaning: one means "empty and rewrite", the other means "keep adding at the end". Log files want >>, or every run wipes the previous record and only the latest run survives; > is for when you want to start clean. The demo script starts with rm -rf to delete the old working directory, so every run starts from the same 6 files and 24 lines, and the numbers in the transcript come out the same every time; run it yourself and you will get the same numbers. One more point that is easy to miss: redirection symbols sit after the command, but they are not arguments to the command. The shell connects the pipes before running the command, so 2> errors.txt at the very end works the same as it would in the middle of the command.
Two more forms are mentioned here just so you recognise them: < feeds a file in as input, so wc -l < errors.txt also counts 1 line, the same result as cat errors.txt | wc -l with one less pipe in the way; and 2>&1 joins the error pipe onto the normal output pipe, meaning "treat errors as normal output too", which comes up a lot when writing logs. Learn >, >>, 2>, < and <<< first; look the rest up when you meet them.
Exit codes: every command leaves a number behind when it goes
This is the most important section in shell scripting, and the easiest to overlook. When a command finishes, it leaves behind a number from 0 to 255, its exit code, kept in $?. The rule runs against intuition: 0 means success, means "yes"; anything else means failure, means "no". The fourth step of the demo measures that rule from end to end: true leaves exit code 0, false leaves exit code 1; looking for TODO in todo.txt finds nothing, so grep leaves exit code 1; looking for TODO in ideas.txt finds it, so the exit code is 0. The same grep command, found or not found, is read off that one number, without reading what it printed.
A pipeline has its own rule for exit codes: by default only the last section counts. In the demo, false | true has two exit codes, 1 and 0: the first section, false, is 1, and the second, true, is 0. By default the whole pipeline reports only the last section, so it reports 0, "success", even though the first half already failed. That is why the demo script turns on pipefail at the top: with it on, the pipeline's exit code is the last non-zero value, which here is 1; with it off, it goes back to 0. Both versions were really measured, one is 1 and the other is 0, not guessed. My judgement is: turn pipefail on in the first line of every script, or a section failing quietly in the middle of a pipeline will stay invisible, and you will end up with a result that looks fine and is missing a piece.
Besides pipefail, there are two more letters to know. set -e means "stop at once if any line fails", instead of carrying on with the error and ending up with a pile of results that make no sense. The demo tries it in a subshell: (set -e; false; echo "never printed"). As soon as false fails, the subshell stops, its exit code is 1, and the line "never printed" is never printed. set -u means "error and stop if you use a variable that was never defined"; the demo tries it on a variable name that was never defined anywhere, and the result is also exit code 1. Put all three together and you get set -euo pipefail, the fixed combination many experienced script writers put at the top of a script: stop on error, error on an undefined variable, and count a failure in any section of a pipeline as a failure of the whole pipeline. The demo script itself uses set -uo pipefail, missing only the e, and the reason is in the section near the end: it is a real pitfall found while writing the demo.
One last warning about the timing of $?: it only holds the previous command's exit code, and any command in between overwrites it. If you want it, use it at once, save it into a variable first and look at it later, as the demo does with false || code_false=$? and grep -q TODO inbox/todo.txt || code_miss=$?. The from-zero guide made the same point about this pitfall, and it is worth repeating here because it is one of the most common beginner mistakes: one extra echo in between, and $? becomes that echo's exit code of 0, and the original failure is gone for good.
Quoting: one space can split a filename in two
The quoting rule was already covered in the other guide: variables expand inside double quotes and stay literal inside single quotes. This section is about what that same rule looks like when it bites a real file. The fifth step of the demo uses a filename with a space in it, "my notes.txt", one of the 6 files in the inbox, 2 lines long. Store that name in a variable called spaced and write for w in $spaced without quotes, and the shell first splits the value at the space and hands the pieces to the loop one at a time: it counts 2 words, my and notes.txt. Write for w in "$spaced" with quotes, and it counts 1 word; the name stays whole. 2 and 1: those two numbers are the price of leaving the quotes off.
What makes this pitfall nasty is that it does not bite most days, only on the day a filename has a space in it. Your script can run a hundred times on your own machine without trouble, then suddenly start failing on a filename with a space, or worse, fail silently and quietly process the wrong file. The backup loop in the demo is written as for f in inbox/*, and the glob expands to 6 files, with the spaced name kept whole as one item, because every time $f appears it sits inside double quotes: cp "$src" "$WORK/backup-20261125/". My judgement is: wherever a variable appears, wrap it in double quotes, written as "$f" and "$src", never bare $f. It is a habit that needs no thinking, and once formed it saves you from most of the baffling errors.
One more word about globs: inbox/*.txt expands to every file ending in .txt, which the demo counts as 4 files. The expansion happens before the command runs, and it is the shell doing it, not ls or cp. If the directory holds no .txt file at all, it does not expand to nothing; it stays literally as inbox/*.txt, the command receives that non-existent path, and the error message will make you think a file was deleted when really nothing matched. When writing a script, first ask "what happens if nothing matches", then decide whether to check first.
test and [ ]: ask before you act
Before doing anything to a file, ask whether it is there. That one question prevents most errors. The sixth step of the demo asks 5 questions, and all 5 said yes: [ -f inbox/meeting.txt ] asks whether it is a real file that exists, yes; [ -d inbox ] asks whether it is a directory, yes; [ -s inbox/old.log ] asks whether the file is non-empty, yes; [ -z "" ] asks whether the string is empty, yes; [ ! -f inbox/nope.txt ] asks whether that non-existent file is indeed absent, yes. Square brackets [ ] are another way of writing the test command, and they need spaces on both sides: [ -f file ] is right, [-f file] fails, because the shell cannot recognise it as a command.
Of those 5 checks, -f and -d are the ones you will use most: before a backup, ask whether the file and the directory are there, which is far cheaper than fixing it after a failure. Two more often go with them: -z asks whether a string is empty and -n asks whether it is non-empty, useful right after reading user input or a command-line argument, before using it. Number comparisons inside square brackets have their own spelling: -lt is less than, -gt is greater than, -eq is equal to; you cannot write < directly, because in the shell that angle bracket means redirection and the meaning changes. Text is compared with =, as in [ "$shop" = "Xiaoman Studio" ], with both sides quoted so a space in the value does not split it open again. This section and the previous one are really the same habit: ask first, then act; and when you act, quote the variable first.
Loops and functions: parts you already know, used in a new way
Loops and functions were covered thoroughly in the other guide, so this section only shows their new use in a backup job and does not re-teach the syntax. The seventh step of the demo starts with a very small function, backup_one, which does one thing: it copies the file it is given into a backup directory, under the fixed date 20261125. Inside the function, local src="$1" declares that the variable only exists inside the function and does not leak outside; $1 is the function's first argument. Outside it, a for loop hands the inbox's 6 files to that function one at a time, and the count comes out as 6 files copied.
Functions have a second use: return only "did it work or not", and use that in an if. The demo writes check_file, which takes a path, returns 0 if the file exists and 1 if it does not. Run it over 3 paths, inbox/meeting.txt and inbox/plan.md are there and inbox/nope.txt is not, and the result is 2 found and 1 missing. Remember this use: a function returning 0 means "yes", returning 1 means "no", the same rule as exit codes, so if check_file "$p"; then just works, without reading anything the function printed. Loops plus functions together make the backup script that closes this guide.
Putting it together: a small backup script you can really use
All the parts are ready, so now they are assembled into a small script that genuinely helps: copy the inbox's 6 files into a backup directory named with a date, rename the log file for the record, and count everything at the end to check. The seventh step of the demo is exactly that, using only what this guide has covered: make the directories first, then process the files one at a time in a for loop, wrap each step in a function, and finish by counting with ls and wc. The measured result: the backup copied 6 files, 445 bytes in total; after renaming old.log to old.log.bak, the backup still holds 6 files, 1 of them a .bak; check_file looked at 3 paths, found 2 and missed 1. The 445 is the sum of the 6 files' byte counts measured with wc -c, not an estimate; run it yourself and you will get the same number.
This script becomes genuinely useful with small changes: swap /tmp/demo252_shell/inbox for your own notes folder, swap the fixed 20261125 for today's date, and every run leaves one more dated backup. The demo uses a fixed date so that every run prints the same output; for daily use, change it to date +%Y%m%d, which takes the date on the day, the standard way to get a date in the shell. One more detail: the demo script starts with rm -rf "$WORK", so that each run begins from a clean state; when you adapt it for your own folders, never copy that line as-is against real folders, because a wrong delete cannot be undone. The whole point of a backup script is that a wrong delete can be recovered; do not let the script itself become the thing that deletes things.

Two real pitfalls found while writing the demo
This section is about things that really happened while writing the demo script, not copied from a manual. The first is that $? and PIPESTATUS cannot both be read after one pipeline: after running false | true, reading $? first and then PIPESTATUS gives you a value that no longer belongs to that pipeline, because the assignment that reads $? is itself a new command and it overwrites PIPESTATUS. The fix is to run the same side-effect-free pipeline twice, once to read PIPESTATUS and once to read $?; both runs give the same numbers, 1 and 0, it just runs one extra time. The lesson is: $? and PIPESTATUS are "look once and they change" values, so save them into a variable the moment you read them, and do not come back for them later.
The second pitfall is more interesting: set -e does not take effect inside an || list. The first version of the demo wrote (set -e; false; echo "never printed") || sete_code=$?, expecting the subshell to stop at false, but the "never printed" line printed anyway, and the exit code was 0. Checking the GNU Bash manual showed why: the manual states plainly that set -e does not make the shell exit for a command inside an && or || list. That is not a bug; it is a rule written in the manual. The fix is to run the subshell bare, with no || after it, and read $? afterwards, which gives the correct result: exit code 1, and that line really never printed. Both pitfalls are left in the demo script's comments, and running it reproduces them.
What you can do after this guide, and where its edges are
After this guide you should be able to do six things: join small commands into a pipeline with pipes, counting lines and finding keywords without saving intermediate files; re-route output and errors with >, >>, 2>, < and <<<, knowing that logs should be appended rather than emptied and rewritten; read $? and PIPESTATUS, knowing that a pipeline with pipefail on exits 1 and with it off exits 0; quote filenames with spaces so they are no longer split in two; ask first with test and [ ] whether a file is there before touching it; and put set -euo pipefail at the top of a script, then wrap backup, rename and check steps in functions to build a small script that runs every day.
The edges need saying plainly too. The site's "Bash Scripting from Zero" guide covers the five beginner topics, variables, quotes, conditionals, loops and functions, plus a file-tidying script; this guide does not repeat those, it covers only pipes, redirection and exit codes, plus a backup script. Both use Bash 5.2.21 and fictional example files, but the numbers are entirely different: that guide has 5 files, 3 txt and 2 md, with sales totalling 40 books; this one has 6 files, 24 lines, 4 TODO lines and a 445-byte backup. The site's Python file I/O guide covers Python's open and json modules, and the Node.js guide covers fs and http; they solve the same kind of problem, "how to handle files", but the language, the modules and the way errors appear are all different, so do not mix the three sets of spellings together.
Three things to try yourself next, none of them needing any package: swap the fixed date 20261125 in the backup script for date +%Y%m%d, run it once a day, and check that the backup directory gains one entry a day; before backing up, add a [ -f "$src" ] check, so a missing file is skipped and noted instead of letting cp fail outright; and change grep -r TODO inbox | wc -l to grep -r TODO inbox | sort | uniq -c, to see how many TODO lines each file has. When you feel that you can string everyday repeated steps together without installing anything, then move on to arrays, getopts argument parsing and signal handling: the from-zero guide named them in its edges too, they all come after this guide, and there is no rush.
Comments (0)
Sources
Related articles
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.