On this page
- How do output redirections work?
- What is a heredoc and how do I write one?
- When should the marker be quoted?
- How do I write a root-owned file from a normal user?
- How do I indent a heredoc inside a function or loop?
- How do I replace a file safely without leaving it half written?
- How do I edit a line inside an existing file?
- What other input tricks are useful?
- Questions
How do output redirections work?
Every process starts with three streams: standard input (0), standard output (1) and standard error (2). Redirections point them at files:
date > run.log # overwrite run.log
uptime >> run.log # append
find / -name "*.conf" 2>/dev/null # hide errors
make > build.log 2>&1 # both streams into one file
make &> build.log # Bash short form of the same
sort < names.txt > sorted.txtOrder matters in > file 2>&1: first standard output goes to the file, then standard error is pointed at wherever output now goes. Written the other way round, errors still reach the terminal. To guard against overwriting an existing file by mistake, enable set -o noclobber; then > refuses to replace a file and >| forces it.
What is a heredoc and how do I write one?
A heredoc feeds several lines of text to a command as its standard input, ending at a line that contains only the chosen marker word:
cat > ~/notes.txt <<EOF
Server: $(hostname)
Created by $USER on $(date +%F)
EOF
cat ~/notes.txtThe marker can be any word; EOF and END are conventional. The closing marker must sit alone at the start of its line, with no spaces before or after it, or Bash keeps reading to the end of the file and warns about a missing delimiter. Heredocs keep long text readable inside a script, far better than a chain of echo lines with escaped quotes.
When should the marker be quoted?
Quote the marker, as in <<'EOF', whenever the text should be written exactly as typed. Leave it unquoted only when you want Bash to substitute variables and commands first:
port=3000
cat > app.env <<EOF
PORT=$port
STARTED=$(date -Is)
EOF
cat > run.sh <<'EOF'
#!/usr/bin/env bash
echo "PID $$ running as $USER on port $PORT"
EOFThe first file contains PORT=3000 and a timestamp. The second keeps $$, $USER and $PORT as literal text, which is what you want when generating another script or a config file that has its own $variables, such as nginx or Caddy configs. Mixing both is possible in an unquoted heredoc by escaping single dollar signs as \$, but a quoted heredoc is clearer.
How do I write a root-owned file from a normal user?
Pipe the content into sudo tee. The redirection in sudo cat > /etc/file is performed by your own shell before sudo starts, so it fails with permission denied:
sudo tee /etc/sysctl.d/90-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 10
net.core.somaxconn = 1024
EOF
sudo sysctl --system | tail -n 3
echo "198.51.100.24 app.example.net" | sudo tee -a /etc/hosts >/dev/nulltee writes its input to the file and also to standard output, which >/dev/null discards. tee -a appends instead of overwriting. An alternative is sudo bash -c 'cat > /etc/file' <<'EOF', but tee is simpler and keeps the elevated part small. Check permissions afterwards with ls -l; new files get mode 644 under the default umask, which suits most config files but not secrets.
How do I indent a heredoc inside a function or loop?
Use <<- with a dash. It strips leading tab characters (not spaces) from every line, including the closing marker:
write_unit() {
sudo tee /etc/systemd/system/myapp.service >/dev/null <<-'EOF'
[Unit]
Description=My app
[Service]
User=deploy
ExecStart=/usr/local/bin/myapp
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
}The indentation in this example must be real tab characters. Many editors convert tabs to spaces, which breaks the closing marker, so check with cat -A (tabs show as ^I). If that feels fragile, keep heredocs flush left even inside indented code. After writing a unit file, run sudo systemctl daemon-reload; the full workflow is in Run an app as a systemd service.
How do I replace a file safely without leaving it half written?
Write to a temporary file in the same directory, check it, then move it over the original. mv within one filesystem is atomic, so readers see either the old or the new file, never a partial one:
conf="/etc/myapp/app.conf"
tmp="$(sudo mktemp "${conf}.XXXX")"
sudo tee "$tmp" >/dev/null <<'EOF'
listen = 127.0.0.1:3000
workers = 4
EOF
sudo chmod 644 "$tmp"
if myapp --check-config "$tmp"; then
sudo mv "$tmp" "$conf"
else
sudo rm -f "$tmp"; echo "config rejected" >&2
fiThe --check-config flag stands for whatever test your software offers, such as nginx -t or caddy validate. mktemp creates a unique name with mode 600, so the chmod restores normal permissions. This pattern also protects you when the disk is full: the write fails and the working config stays untouched.
How do I edit a line inside an existing file?
For small, repeatable changes use sed -i, and make the change idempotent so running the script twice does no harm:
f=/etc/ssh/sshd_config.d/50-local.conf
sudo touch "$f"
if grep -q "^PasswordAuthentication" "$f"; then
sudo sed -i "s/^PasswordAuthentication.*/PasswordAuthentication no/" "$f"
else
echo "PasswordAuthentication no" | sudo tee -a "$f" >/dev/null
fi
sudo sshd -t && sudo systemctl reload sshThe pattern is: change the line if it exists, add it if not. Always validate before reloading; sshd -t catches typos that could lock you out. On Rocky and Alma the service is called sshd instead of ssh. Before touching SSH settings, keep a second session open and read the SSH keys and hardening tutorial.
What other input tricks are useful?
A here-string (<<<) passes one string as input, and process substitution (<( )) lets a command read another command's output as if it were a file:
read -r a b <<< "198.51.100.24 2001:db8:4f2a::24"
wc -w <<< "count these four words"
diff <(sort old.txt) <(sort new.txt)
exec 3>> /var/tmp/job.log
echo "step 1 done" >&3
exec 3>&-The exec 3>> line opens a file on descriptor 3 once, so many writes go through it without reopening the file each time; 3>&- closes it. To send all later output of a script to a log while still seeing it, use exec > >(tee -a /var/tmp/job.log) 2>&1 near the top. Reading files line by line is covered in for, while and until loops.
Questions about Heredocs and writing to files
Why do I get warning: here-document delimited by end-of-file?
Bash never found the closing marker. It probably has spaces around it, a Windows carriage return after it, or is indented with spaces under <<-.
Can I use a heredoc with ssh?
Yes: ssh deploy@198.51.100.24 bash -s <<'EOF' runs the lines on the remote server. Quote the marker so variables expand there, not locally.
How do I empty a file without deleting it?
Use : > file or truncate -s 0 file. The file keeps its owner and permissions, and a program holding it open keeps writing to it.
Does tee keep the existing file permissions?
Yes, when it overwrites an existing file the owner and mode stay. A new file gets the default mode, so set chmod for secrets right away or create it with install -m 600 first.
How do I write a file only when the content changed?
Write to a temp file, compare with cmp -s new old, and move it only if they differ. That avoids needless service reloads.