The shell does much more than redirect > and <. The here-doc embeds a block of text directly in a script, without a temporary file. Process substitution makes the output of a command pass for a file. And xargs turns any stream into arguments of a command, with or without parallelism.
These techniques extend the RHCSA objective "Use input-output redirection (>, >>, |, 2>, etc.)": simple redirections are covered in the fundamentals, this page deals with what an administration script actually does with them.
What you will learn
- Create multi-line text content with
<< EOFin scripts - Control variable interpolation in a here-doc
- Compare two command outputs with
diff <(...)without a temporary file - Extract common or unique lines with
command process substitution - Turn a stream into arguments with
xargs,-I {},-n1and-P - Protect file names with spaces with
-print0 | xargs -0
Prerequisites
- Command of the bash shell (redirections
>,<, pipes|) - Basics of the text processing commands (
grep,sort,diff)
Lab A, local shell: every example runs in your terminal, without root rights. Create a working directory and the two sample lists that the diff, comm and xargs sections reuse. The outputs of this page were measured on Debian 13 with these exact files.
mkdir -p ~/Projets/lab-linux/exploiter/redirections-avanceescd ~/Projets/lab-linux/exploiter/redirections-avanceesprintf '%s\n' alpha bravo charlie delta echo > liste1.txtprintf '%s\n' alpha charlie echo foxtrot golf > liste2.txtHere-doc: a block of text without a file
A here-doc (here document) sends a multi-line block of text to the standard input of a command, straight from the script. Everything between << EOF and the closing EOF line is passed to the command, with no intermediate file to create and then delete.
Basic syntax
The simplest form feeds cat, which copies its input to the screen. It is the most direct way to print a formatted block of text, or to redirect it to a file.
cat << 'EOF'Server : web01IP : 192.168.1.10Role : nginx reverse proxyEOFThe marker can be called EOF, END, HEREDOC or anything else: EOF is only a convention. What is strict is the closing: the final marker must be alone on its line, with no leading space, identical to the opening marker.
With variable interpolation
When the marker is not quoted (<< EOF), the shell interprets the content before sending it: $VAR is replaced by its value and $(cmd) by the output of the command. It is the form to choose for a report or a configuration that depends on the execution context.
SERVER="web01"IP="192.168.1.10"
cat << EOFReport generated on $(date +%Y-%m-%d)Host : $SERVERAddress : $IPEOFThe output carries the values and today's date, not the variable names:
Report generated on 2026-09-29Host : web01Address : 192.168.1.10Without interpolation: quoted marker
Quoting the marker (<< 'EOF') turns off every expansion: the text is copied as is, $ included. It is essential to generate a script or a template that itself contains shell variables, otherwise they would be replaced by empty values at write time.
cat << 'EOF'To reach $SERVER, type: ssh $USER@$IPExpansion turned off: $(date) will not be replacedEOFThe output is literal, line for line. Remember the rule in one sentence: << EOF interprets, << 'EOF' copies. The choice must be explicit, never left to chance.
Create a file directly
The cat > file << 'EOF' combination writes the content of the here-doc into a file: > creates or overwrites it, and the quoted marker guarantees a literal copy. That is what protects an nginx configuration, whose $host or $remote_addr variables must arrive intact. Nothing is printed on screen, and >> would append at the end instead of overwriting.
sudo tee /etc/nginx/conf.d/app.conf > /dev/null << 'EOF'server { listen 80; server_name app.local; location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; }}EOFUnder /etc, you need root rights. sudo cat > /etc/... does not work, because the > redirection is done by your shell, before sudo. Hence sudo tee, which opens the file itself, the > /dev/null avoiding the echo on screen. Then check the syntax with sudo nginx -t before any reload.
Indented here-doc with <<-
In a function or an if block, a here-doc stuck to column 1 breaks the reading of the script. The <<- variant removes the leading tabs of each line, closing marker included, which allows clean indentation.
generate_config() { local host=$1 cat <<-EOF Host : $host Date : $(date +%Y-%m-%d) Status : active EOF}
generate_config "web01"Only tabs are removed, never spaces: measured on bash 5.2, a line starting with a tab then two spaces comes out with its two spaces. Yet many editors convert tabs into spaces, and the closing marker is then no longer recognised.
Feed commands with a here-doc
The here-doc is not reserved for cat: it feeds any command that reads its standard input. A SQL client receives its queries this way, and sed a text to transform, with no file to maintain next to the script.
# Pass SQL queries to the mysql client (the password is prompted)mysql -u root -p my_db << 'EOF'SELECT user, host FROM mysql.user;SHOW DATABASES;EOF# Feed sed with a here-docsed 's/prod/staging/' << 'EOF'Server prod01Database prod-dbConfig: prod.confEOFThe second command prints the three lines with staging instead of the first occurrence of prod. The same principle feeds xargs, shown further down with the package list.
Process substitution: <(cmd) treats an output as a file
Process substitution passes the output of a command where a tool expects a file name. Bash runs the command and provides in its place a path of the form /dev/fd/N, which the tool opens like an ordinary file. No temporary file is written to disk.
diff between two command outputs
Without process substitution, comparing two outputs takes four steps: write two temporary files, compare them, then delete them, hoping the script does not stop in between.
# Classic method: 4 stepssort liste1.txt > /tmp/l1.txtsort liste2.txt > /tmp/l2.txtdiff /tmp/l1.txt /tmp/l2.txtrm /tmp/l1.txt /tmp/l2.txtWith process substitution, the comparison fits in one line, and there is nothing to clean up:
diff <(sort liste1.txt) <(sort liste2.txt)2d1< bravo4d2< delta5a4,5> foxtrot> golfRead 2d1 as "delete line 2 of the first file", and 5a4,5 as "add after line 5 the lines 4 to 5 of the second". diff exits with code 1 as soon as the inputs differ, which lets you use it as a test in a script.
comm with process substitution
comm compares two sorted files and arranges their lines in three columns: unique to the first, unique to the second, common to both. Its options suppress columns, and process substitution gives it sorted inputs without pre-sorting on disk.
# Lines present in liste1 but not in liste2comm -23 <(sort liste1.txt) <(sort liste2.txt)bravodelta| Option | Prints | Result on the sample lists |
|---|---|---|
-23 | Only column 1 (liste1 only) | bravo, delta |
-13 | Only column 2 (liste2 only) | foxtrot, golf |
-12 | Only the common lines | alpha, charlie, echo |
Concrete case: list the human accounts that are not logged in, by crossing /etc/passwd with who. The $3 < 65534 bound excludes the nobody account, whose UID is also above 1000.
comm -23 \ <(awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwd | sort) \ <(who | awk '{print $1}' | sort -u)Keep the variables of a loop with < <(...)
A while read loop placed after a pipe runs in a subshell: the variables it changes vanish at the end of the pipe. Redirecting process substitution into the loop with done < <(cmd) makes it run in the current shell, and the counter survives.
n=0grep -h a liste1.txt liste2.txt | while read -r line; do n=$((n+1)); doneecho "n=$n" # n=0: the counter stayed in the subshell
n=0while read -r line; do n=$((n+1)); done < <(grep -h a liste1.txt liste2.txt)echo "n=$n" # n=6The first < is an ordinary redirection, the second is part of <(...): the space between the two is mandatory.
xargs: turn a stream into arguments
xargs reads its standard input, splits it on blanks (spaces, tabs, newlines) and passes each element as an argument to the command that follows. The difference with a plain pipe: the target command receives arguments, not a stream to read.
Basic usage
The first benefit of xargs is to get around the size limit of the command line (getconf ARG_MAX is 2,097,152 bytes on Debian 13). Beyond it, the kernel refuses to start the command: /bin/echo $(seq 1 3000000) fails with Argument list too long. xargs, on the other hand, splits the list into batches that respect the limit: seq 1 3000000 | xargs /bin/echo succeeds in 175 calls.
# Count the lines of every .txt, whatever their numberfind . -name "*.txt" -print0 | xargs -0 wc -lfind produces the list, xargs distributes it. With many files, wc is called several times, and each call prints its own total line. The ls *.txt | xargs form gets around nothing: the shell expands *.txt into arguments of ls, and the limit strikes before xargs even runs.
-I {}: place the argument at a precise spot
By default, xargs appends the arguments at the end of the command. cat list.txt | xargs cp backup/ would give cp backup/ file1 file2, a source and destination inversion. The -I {} option defines a placeholder that each input replaces, wherever it appears.
# Copy files listed in a file to a backup directorymkdir -p backupprintf '%s\n' liste1.txt liste2.txt | xargs -I {} cp {} backup/# Create a .bak copy of each listfind . -maxdepth 1 -name "liste*.txt" | xargs -I {} cp {} {}.bakThe placeholder can appear several times, as in {}.bak. The trade-off: -I reads one input per line and runs one call per input, so it is slower than the default grouping on large volumes.
-n1: one call per argument
Without an option, xargs groups as many arguments as possible per call, to start as few processes as possible. -n1 on the contrary forces a separate call per input, useful when the command accepts a single argument or when you want one output per file.
echo "liste1.txt liste2.txt" | xargs -n1 wc -l5 liste1.txt5 liste2.txtWithout -n1, the same command runs a single wc -l liste1.txt liste2.txt, which adds a 10 total line.
-P: parallel processing
The -P option sets the number of simultaneous processes. It combines with -n1 or -I {}, otherwise xargs would group a short list into a single call, and would have nothing to parallelise.
# Compress the archived logs of a working directory, one gzip per corefind ./archives -name "*.log" -print0 | xargs -0 -n1 -P"$(nproc)" gzip
# Download a list of URLs, 8 at a timexargs -P8 -I {} curl -fsSLO {} < urls.txtDo not run this gzip on /var/log: compressing the log a service is writing breaks log rotation, which is the job of logrotate.
Here-doc + xargs: the most readable combination
A here-doc gives xargs a list written in the script, one element per line. The list reads and changes like a configuration, with no external file to keep up to date and no loop to write.
# Install a list of packages (Debian/Ubuntu; on RHEL: dnf install -y)xargs sudo apt-get install -y << 'EOF'gitcurljqtreeEOF# Back up a few files of /etc listed in the scriptmkdir -p /tmp/backupxargs -I {} cp /etc/{} /tmp/backup/ << 'EOF'passwdgrouphostshostnameEOFCommon traps
The four traps below have one thing in common: none of them produces a clear error at the right place. The badly closed here-doc swallows the end of the script, the sh shebang fails on a syntax that works in the terminal, and xargs splits or runs the command where you do not expect it.
Here-doc: closing on a line of its own
The closing marker must be alone, with no space, in column 1. Indented with spaces, it is not recognised, and the here-doc swallows every following line of the script as text.
# ❌ ERROR: spaces before EOFcat << 'EOF'content EOFecho afterMeasured on bash 5.2: echo after is never run, it is printed as text. Bash only reports the problem at the end of the file, with a mere warning, here-document at line 1 delimited by end-of-file, and the script exits with code 0. Only the <<- variant tolerates tabs in front of the marker.
Process substitution: bash required
A script run by sh does not know <(...). The trap is that the same line works in the terminal, which is an interactive bash. On Debian, where sh is dash, the error hits when the script runs.
#!/bin/sh# ❌ ERROR: dash does not know <(...)diff <(sort f1) <(sort f2)Dash answers Syntax error: "(" unexpected, with code 2. The solution is to change the shebang to #!/bin/bash, and to run the script with ./script.sh or bash script.sh, never sh script.sh.
xargs and names with spaces
By default, xargs splits on blanks and interprets quotes: a file name that contains a space or an apostrophe breaks the command.
# ❌ "fichier avec espace.txt" becomes 3 argumentsls *.txt | xargs wc -lwc: fichier: No such file or directorywc: avec: No such file or directorywc: espace.txt: No such file or directoryAn apostrophe does worse: xargs stops on unmatched single quote. The fix is the null separator: -print0 ends each name with a null byte, the only byte forbidden in a file path, and xargs -0 splits on that same byte, without interpreting quotes.
find . -name "*.txt" -print0 | xargs -0 wc -lxargs: nothing to process
If the stream is empty, GNU xargs still runs the command once, without arguments. rm then fails cleanly (missing operand), but other commands act on a default value: printf '' | xargs du -sh measures the current directory. The -r option (long form --no-run-if-empty) suppresses this empty call.
# Safe cleanup, even when find finds nothingfind . -name "*.bak" -print0 | xargs -0 -r rmSummary table
This table sums up each technique with its syntax and the use that justifies it. Use it to pick the right form when writing a script: here-doc to produce text, process substitution to compare or read outputs, xargs to apply a command to a list.
| Technique | Syntax | Typical use |
|---|---|---|
| Here-doc with interpolation | << EOF | Generate configs in a script |
| Here-doc without interpolation | << 'EOF' | Generate code or templates |
| Indented here-doc | <<- EOF | Readability in functions (tabs only) |
| Process substitution | <(cmd) | diff, comm, on-the-fly comparisons |
| Loop in the current shell | done < <(cmd) | Keep the variables of a while read loop |
| Basic xargs | cmd | xargs cmd2 | Apply a command to a list |
| xargs with position | ... | xargs -I {} cmd {} | Renaming, copying, transformation |
| Parallel xargs | ... | xargs -n1 -P4 cmd | Bulk compression, downloads |
| Protect spaces | find -print0 | xargs -0 | File names with spaces or apostrophes |
Key points
<< EOFinterprets variables;<< 'EOF'does not, the choice is explicit, not accidental.- To write under
/etc,sudo tee file > /dev/null << 'EOF', neversudo cat > file. - Process substitution
<(cmd)avoids temporary files, anddone < <(cmd)keeps the variables of a loop. xargsgets around theArgument list too longlimit by splitting the list into batches.- Always use
-print0 | xargs -0as soon as file names may contain spaces or apostrophes. - Process substitution does not work with
sh: check the shebang in scripts.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Advanced tar: backups, compression and selective restore
A new full quiz with random questions
Work again only on the questions you missed