Input, output and redirection
Every program starts with three open streams. Bash lets you connect them to files, to other programs, or to nothing at all. This is what makes small commands so powerful together.
| Stream | Number | Default |
|---|---|---|
| stdin: standard input | 0 |
Your keyboard |
| stdout: standard output | 1 |
Your screen |
| stderr: standard error | 2 |
Your screen |
Normal results go to stdout; error messages and warnings go to stderr. Keeping them separate means you can save the results and still see the errors.
Writing to files
echo "first line" > notes.txt # create or OVERWRITE
echo "second line" >> notes.txt # append
cat notes.txt
echo "replaced" > notes.txt
cat notes.txtfirst line second line replaced
⚠️
>empties the file before the command even starts.sort data.txt > data.txtgives you an empty file. Write to a new file, then rename it.
set -o noclobber makes > refuse to overwrite existing files (use >| to force it). Some people turn it on in their ~/.bashrc as a safety net.
Redirecting errors
ls /etc/hostname /nope > found.txt
echo "--- found.txt:"
cat found.txt
ls /etc/hostname /nope 2> errors.txt
echo "--- errors.txt:"
cat errors.txt
ls /etc/hostname /nope > all.txt 2>&1
echo "--- all.txt:"
cat all.txt
ls /etc/hostname /nope 2>/dev/nullls: cannot access '/nope': No such file or directory --- found.txt: /etc/hostname /etc/hostname --- errors.txt: ls: cannot access '/nope': No such file or directory --- all.txt: ls: cannot access '/nope': No such file or directory /etc/hostname /etc/hostname
| Syntax | Meaning |
|---|---|
> file |
stdout to file |
2> file |
stderr to file |
> file 2>&1 or &> file |
both to the same file |
2>/dev/null |
throw errors away |
> /dev/null 2>&1 |
silence a command completely |
/dev/null is a special file that swallows everything written to it. 2>&1 means "send stream 2 wherever stream 1 is going right now", so the order matters: > file 2>&1 works, 2>&1 > file doesn't.
Printing errors from your own scripts
Send messages meant for humans (warnings, errors, progress) to stderr with >&2. Then the script's real output stays clean when someone pipes or saves it:
#!/usr/bin/env bash
echo "fetching data…" >&2
echo "id,name"
echo "1,Asha"
echo "2,Ravi"
echo "done" >&2bash fetch.sh > data.csv
echo "--- data.csv:"
cat data.csvfetching data… done --- data.csv: id,name 1,Asha 2,Ravi
Pipes
A pipe | connects one command's stdout to the next command's stdin. Each command does one small job:
printf "pear\napple\nfig\napple\nbanana\npear\napple\n" > fruit.txt
sort fruit.txt | uniq -c | sort -rn | head -3
grep -c apple fruit.txt
cat /etc/passwd | cut -d: -f1 | sort | head -3 3 apple
2 pear
1 fig
3
_apt
backup
binRead the first pipeline left to right: sort the lines, count repeated lines, sort by that count (highest first), keep the top 3. That's a word-frequency report in one line.
Pipes only carry stdout. To send errors through a pipe too, use 2>&1 | (or |&).
tee: save and show
tee writes its input to a file and passes it on, which is great for logging:
echo "build started" | tee build.log
echo "tests passed" | tee -a build.log > /dev/null
cat build.logbuild started build started tests passed
command | sudo tee /etc/some.conf is also the standard trick to write a root-owned file, because sudo echo x > file doesn't work (the redirection runs as you).
Reading input: read
read takes one line from stdin and stores it in variables:
#!/usr/bin/env bash
read -rp "What's your name? " name
read -rp "How old are you? " age
echo "Hi $name, next year you'll be $(( age + 1 ))."bash ask.shWhat's your name? Asha How old are you? 31 Hi Asha, next year you'll be 32.
(The answers Asha and 31 were typed in. When input comes from a file or pipe, as here, the typed text isn't echoed to the screen.)
| Option | Meaning |
|---|---|
-r |
Keep backslashes literally. Always use it. |
-p "text" |
Show a prompt first |
-s |
Silent: don't show what's typed (passwords) |
-t 10 |
Give up after 10 seconds |
-a arr |
Split the line into an array |
Reading a file line by line
The safe, standard loop:
printf "Asha 31 Pune\nRavi 28 Delhi\nLee 35 Seoul\n" > people.txt
while IFS=' ' read -r name age city; do
echo "$name ($age) lives in $city"
done < people.txtAsha (31) lives in Pune Ravi (28) lives in Delhi Lee (35) lives in Seoul
read splits each line into the variables on the characters in IFS (spaces and tabs by default). The last variable gets the rest of the line. Use IFS=, for simple CSV. done < file feeds the whole loop from the file.
💡 Don't write
for line in $(cat file): that splits on every space, not on lines.
Here documents
A here document (<<EOF) feeds several lines into a command's stdin. It's perfect for generating config files or messages:
app="shop"
port=8080
cat <<EOF > app.conf
# generated by deploy.sh
name = $app
port = $port
url = http://localhost:$port
EOF
cat app.conf
cat <<'EOF'
Quoted EOF: $app stays literal
EOF# generated by deploy.sh name = shop port = 8080 url = http://localhost:8080 Quoted EOF: $app stays literal
<<EOFexpands variables inside;<<'EOF'doesn't (useful for scripts that contain$).<<-EOFlets you indent the lines with tabs (not spaces).- The closing
EOFmust be alone on its line. Any word works;EOFis tradition.
A here string <<< sends a single string:
tr 'a-z' 'A-Z' <<< "shout this"
read -r first rest <<< "one two three"
echo "first=$first rest=$rest"SHOUT THIS first=one rest=two three
Process substitution
<(command) lets you pass a command's output to a program that expects a file name. The classic use is comparing two outputs:
printf "a\nb\nc\n" > old.txt
printf "a\nc\nd\n" > new.txt
diff <(sort old.txt) <(sort new.txt)2d1 < b 3a3 > d
Practice
- Run
find / -name "*.conf"and save only the results toconfs.txt, hiding every "Permission denied" error. - Write
ask_color.shthat asks for a favourite colour and prints it in uppercase usingtr. - Generate a file
index.htmlfrom a here document containing a title from a variable. - Read
people.txtabove and print only the people older than 30 (you'll needif (( age > 30 ))).
1.What does command > out.txt 2>&1 do?
2.Why do scripts send progress messages to >&2?
3.What's wrong with sort names.txt > names.txt?
4.Which loop reads a file line by line correctly?