Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Beginner

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

bash
echo "first line" > notes.txt     # create or OVERWRITE
echo "second line" >> notes.txt   # append
cat notes.txt
echo "replaced" > notes.txt
cat notes.txt
Output
first line
second line
replaced

⚠️ > empties the file before the command even starts. sort data.txt > data.txt gives 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

bash
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/null
Output
ls: 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:

fetch.sh
#!/usr/bin/env bash
echo "fetching data…" >&2
echo "id,name"
echo "1,Asha"
echo "2,Ravi"
echo "done" >&2
bash
bash fetch.sh > data.csv
echo "--- data.csv:"
cat data.csv
Output
fetching 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:

bash
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
Output
      3 apple
      2 pear
      1 fig
3
_apt
backup
bin

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

bash
echo "build started" | tee build.log
echo "tests passed" | tee -a build.log > /dev/null
cat build.log
Output
build 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:

ask.sh
#!/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
bash ask.sh
Output
What'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:

bash
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.txt
Output
Asha (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:

bash
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
Output
# generated by deploy.sh
name = shop
port = 8080
url  = http://localhost:8080
Quoted EOF: $app stays literal
  • <<EOF expands variables inside; <<'EOF' doesn't (useful for scripts that contain $).
  • <<-EOF lets you indent the lines with tabs (not spaces).
  • The closing EOF must be alone on its line. Any word works; EOF is tradition.

A here string <<< sends a single string:

bash
tr 'a-z' 'A-Z' <<< "shout this"
read -r first rest <<< "one two three"
echo "first=$first rest=$rest"
Output
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:

bash
printf "a\nb\nc\n" > old.txt
printf "a\nc\nd\n" > new.txt
diff <(sort old.txt) <(sort new.txt)
Output
2d1
< b
3a3
> d

Practice

  1. Run find / -name "*.conf" and save only the results to confs.txt, hiding every "Permission denied" error.
  2. Write ask_color.sh that asks for a favourite colour and prints it in uppercase using tr.
  3. Generate a file index.html from a here document containing a title from a variable.
  4. Read people.txt above and print only the people older than 30 (you'll need if (( age > 30 ))).
✎ Check your understanding

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?

← Quoting and expansion