Unit 3: Searching and pipes · Lesson 3 of 6 · 16 min

Redirection and find

Save output to files, silence errors, read exit codes and search the disk by name and size.

mission

You are
You are hunting for data that should not be public.
Situation
The scanner asked for backups. The web root is large, and you want a saved list of anything suspicious.
Goal
Search the web root by size and name and save the results.
Hand in
The path of any oversized file in the web root.

Where output goes

  1. 0 standard inputkeyboard, or < file
  2. 1 standard outputscreen, > file, >> file, | next
  3. 2 standard errorscreen, or 2>/dev/null
01

Write and append

learner@root-lab
echo hello > t.txt
echo again >> t.txt
cat t.txt
hello
again

you should see > replaces the file, >> adds to the end.

02

Silence errors and read the exit code

learner@root-lab
ls /nonexistent
ls: cannot access '/nonexistent': No such file or directory
ls /nonexistent 2>/dev/null
echo $?
2

you should see No message the second time, but the exit code still says it failed. 0 means success.

defender tip Monitoring checks and scripts trust exit codes, not messages.

03

Find big and named files

learner@root-lab
find /var/www -size +5M
/var/www/html/assets/site-backup.tar.gz
find /var/www -name '*.css'
/var/www/html/assets/css/site.css
find /var/www -size +5M > ~/big-files.txt

you should see A 6 MB backup inside the public web root. Anyone who guesses the name can download it.

CommandWhat it does
cmd > fileSave output, replacing the file
cmd >> fileAppend output
cmd 2>/dev/nullDiscard errors
echo $?Exit code of the last command
find dir -name 'x*'Find by name
find dir -size +5MFind by size

What a defender takes away

  1. 1>, >> and 2> decide where output goes.
  2. 2Exit codes tell scripts what happened.
  3. 3find searches by name, size, owner and permission.

Questions

0 of 2 solved

Answer each one from what you find on your lab machine.

  1. Show hint

    find /var/www -size +5M

  2. Show hint

    Run it, then echo $?