Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Advanced redirections, here-doc and xargs

By updated

Improve this page

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 << EOF in scripts
  • Control variable interpolation in a here-doc
  • Compare two command outputs with diff <(...) without a temporary file
  • Extract common or unique lines with comm and process substitution
  • Turn a stream into arguments with xargs, -I {}, -n1 and -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.

Terminal window
mkdir -p ~/Projets/lab-linux/exploiter/redirections-avancees
cd ~/Projets/lab-linux/exploiter/redirections-avancees
printf '%s\n' alpha bravo charlie delta echo > liste1.txt
printf '%s\n' alpha charlie echo foxtrot golf > liste2.txt

Here-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.

Terminal window
cat << 'EOF'
Server : web01
IP : 192.168.1.10
Role : nginx reverse proxy
EOF

The 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.

Terminal window
SERVER="web01"
IP="192.168.1.10"
cat << EOF
Report generated on $(date +%Y-%m-%d)
Host : $SERVER
Address : $IP
EOF

The output carries the values and today's date, not the variable names:

Report generated on 2026-09-29
Host : web01
Address : 192.168.1.10

Without 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.

Terminal window
cat << 'EOF'
To reach $SERVER, type: ssh $USER@$IP
Expansion turned off: $(date) will not be replaced
EOF

The 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.

Terminal window
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;
}
}
EOF

Under /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.

Terminal window
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.

Terminal window
# 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
Terminal window
# Feed sed with a here-doc
sed 's/prod/staging/' << 'EOF'
Server prod01
Database prod-db
Config: prod.conf
EOF

The 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.

Terminal window
# Classic method: 4 steps
sort liste1.txt > /tmp/l1.txt
sort liste2.txt > /tmp/l2.txt
diff /tmp/l1.txt /tmp/l2.txt
rm /tmp/l1.txt /tmp/l2.txt

With process substitution, the comparison fits in one line, and there is nothing to clean up:

Terminal window
diff <(sort liste1.txt) <(sort liste2.txt)
2d1
< bravo
4d2
< delta
5a4,5
> foxtrot
> golf

Read 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.

Terminal window
# Lines present in liste1 but not in liste2
comm -23 <(sort liste1.txt) <(sort liste2.txt)
bravo
delta
OptionPrintsResult on the sample lists
-23Only column 1 (liste1 only)bravo, delta
-13Only column 2 (liste2 only)foxtrot, golf
-12Only the common linesalpha, 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.

Terminal window
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.

Terminal window
n=0
grep -h a liste1.txt liste2.txt | while read -r line; do n=$((n+1)); done
echo "n=$n" # n=0: the counter stayed in the subshell
n=0
while read -r line; do n=$((n+1)); done < <(grep -h a liste1.txt liste2.txt)
echo "n=$n" # n=6

The 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.

Terminal window
# Count the lines of every .txt, whatever their number
find . -name "*.txt" -print0 | xargs -0 wc -l

find 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.

Terminal window
# Copy files listed in a file to a backup directory
mkdir -p backup
printf '%s\n' liste1.txt liste2.txt | xargs -I {} cp {} backup/
Terminal window
# Create a .bak copy of each list
find . -maxdepth 1 -name "liste*.txt" | xargs -I {} cp {} {}.bak

The 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.

Terminal window
echo "liste1.txt liste2.txt" | xargs -n1 wc -l
5 liste1.txt
5 liste2.txt

Without -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.

Terminal window
# Compress the archived logs of a working directory, one gzip per core
find ./archives -name "*.log" -print0 | xargs -0 -n1 -P"$(nproc)" gzip
# Download a list of URLs, 8 at a time
xargs -P8 -I {} curl -fsSLO {} < urls.txt

Do 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.

Terminal window
# Install a list of packages (Debian/Ubuntu; on RHEL: dnf install -y)
xargs sudo apt-get install -y << 'EOF'
git
curl
jq
tree
EOF
Terminal window
# Back up a few files of /etc listed in the script
mkdir -p /tmp/backup
xargs -I {} cp /etc/{} /tmp/backup/ << 'EOF'
passwd
group
hosts
hostname
EOF

Common 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.

Terminal window
# ❌ ERROR: spaces before EOF
cat << 'EOF'
content
EOF
echo after

Measured 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.

Terminal window
# ❌ "fichier avec espace.txt" becomes 3 arguments
ls *.txt | xargs wc -l
wc: fichier: No such file or directory
wc: avec: No such file or directory
wc: espace.txt: No such file or directory

An 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.

Terminal window
find . -name "*.txt" -print0 | xargs -0 wc -l

xargs: 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.

Terminal window
# Safe cleanup, even when find finds nothing
find . -name "*.bak" -print0 | xargs -0 -r rm

Summary 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.

TechniqueSyntaxTypical use
Here-doc with interpolation<< EOFGenerate configs in a script
Here-doc without interpolation<< 'EOF'Generate code or templates
Indented here-doc<<- EOFReadability in functions (tabs only)
Process substitution<(cmd)diff, comm, on-the-fly comparisons
Loop in the current shelldone < <(cmd)Keep the variables of a while read loop
Basic xargscmd | xargs cmd2Apply a command to a list
xargs with position... | xargs -I {} cmd {}Renaming, copying, transformation
Parallel xargs... | xargs -n1 -P4 cmdBulk compression, downloads
Protect spacesfind -print0 | xargs -0File names with spaces or apostrophes

Key points

  • << EOF interprets variables; << 'EOF' does not, the choice is explicit, not accidental.
  • To write under /etc, sudo tee file > /dev/null << 'EOF', never sudo cat > file.
  • Process substitution <(cmd) avoids temporary files, and done < <(cmd) keeps the variables of a loop.
  • xargs gets around the Argument list too long limit by splitting the list into batches.
  • Always use -print0 | xargs -0 as 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

6 questions
6 min
70% to pass

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