Bash Tutorial · Bash Basics · Lesson 6 of 30

Bash Viewing Files

Read files with cat, head, tail and less, and count lines, words and bytes with wc.

Create a free account to save this page, take notes and track your progress. Sign in

Printing files

  • cat file prints a whole file.
  • head -n 5 file prints the first 5 lines; tail -n 5 the last 5.
  • tail -f app.log follows a growing log file (Ctrl+C to stop).
  • less file opens a scrollable viewer (q quits, /text searches).
head, tail and a range of lines
seq 1 10 > numbers.txt
head -n 3 numbers.txt
echo ---
tail -n 2 numbers.txt
echo ---
sed -n '4,6p' numbers.txt

Output

1
2
3
---
9
10
---
4
5
6

Run this on your computer — see “Get Started” for setup.

Counting

wc -l counts lines, wc -w words, wc -c bytes.

Counting lines and words
printf 'error: disk full\ninfo: started\nerror: timeout\n' > app.log
wc -l app.log
wc -w < app.log
grep -c error app.log

Output

3 app.log
7
2

Run this on your computer — see “Get Started” for setup.

Test yourself

Which command shows the last 20 lines of a log and keeps printing new lines?

  1. head -n 20 app.log
  2. cat -f app.log
  3. tail -n 20 -f app.log
  4. less +20 app.log
Show answer

Answer: tail -n 20 -f app.log

Was this page helpful?