Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 95 ยท Practice and Review

Practice Problems: Commands and Text

15 graded Linux practice problems with hints and verified solutions: files, permissions, links, find, grep, sed, awk, sort, redirection, tar and pipelines.

You learn the shell by typing commands, not by reading about them. This page collects 15 problems that cover the first half of the course, ordered from beginner to advanced inside each group. Each problem has a short task, a hint, an editor with the set-up already written, and a hidden solution.

Every editor runs as given: it creates the sample files and then does nothing, and the comments at the bottom show the output your commands should print. Add your commands below the set-up, press Run, and compare.

  • Try first, peek later. A few minutes of being stuck is where the learning happens. Open the hint before the solution.
  • Compare, don't copy. Many problems have more than one correct answer. Your pipeline can differ from ours as long as the output is the same, and ours often explains a flag worth knowing.
  • Every editor starts fresh. Files you create vanish after the run, so each problem builds its own sample data and you cannot damage anything.
  • Quote your variables and your patterns. If something prints strangely, the usual cause is an unquoted $var or a glob that the shell expanded too early. See Quoting and Expansion.

Keep the cheat sheet open in another tab. When you are comfortable here, continue with the scripting and pipeline problems.

Files and directories

These problems practise creating files, copying and moving, wildcards, permissions, links and find.

1. A project skeleton in one command (Beginner)

Create this layout inside the current directory: a directory shop containing the directories src, tests and docs/api, an empty file shop/README.md and an empty file shop/src/main.sh. Use a single mkdir -p command with brace expansion for the directories, then print every path under shop in sorted order with find.

Hint: mkdir -p shop/{src,tests} expands to two arguments before mkdir even starts.

Bash Exercise 1: A project skeleton in one command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
mkdir -p shop/{src,tests,docs/api}
touch shop/README.md shop/src/main.sh
find shop | sort

The shell expands shop/{src,tests,docs/api} into three words, and -p creates parent directories as needed, so shop/docs appears on the way to shop/docs/api. find shop prints in directory order, which is not alphabetical, so the sort makes the output stable.

2. Copy and rename with a loop (Beginner)

The directory contains report-1.txt, report-2.txt, report-3.txt, notes.md and report-draft.md. Copy only the three report-N.txt files into the directory backup, changing the extension to .bak, then list backup.

Hint: the pattern report-*.txt does not match report-draft.md. Inside the loop, ${f%.txt} removes the extension.

Bash Exercise 2: Copy and rename with a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
for f in report-*.txt; do
  cp -- "$f" "backup/${f%.txt}.bak"
done
ls backup

The glob expands before the loop runs, so f takes the values report-1.txt, report-2.txt and report-3.txt. ${f%.txt} strips the shortest .txt from the end, and -- protects cp from names that start with a dash.

3. Permissions and umask (Beginner)

run.sh is a script and key.txt holds a secret. Make run.sh executable and readable by everyone but writable only by its owner (mode 755), and make key.txt readable and writable only by its owner (600). Run ./run.sh, then print each file's octal mode with stat -c '%a %n'. Finally create an empty file new.txt in a subshell where umask 077 is set and print its mode too.

Hint: umask changes only the shell it runs in, so wrap it in parentheses to keep the change from leaking.

Bash Exercise 3: Permissions and umask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
chmod 755 run.sh
chmod 600 key.txt
./run.sh
stat -c '%a %n' run.sh key.txt
( umask 077; touch new.txt )
stat -c '%a %n' new.txt

Octal digits are the sum of read (4), write (2) and execute (1) for owner, group and others: 755 is rwxr-xr-x, 600 is rw-------. The umask is subtracted from the default mode of new files (666), so 077 leaves 600.

Create hard.txt as a hard link and soft.txt as a symbolic link to original.txt. Append the line v2 through soft.txt. Print the link count of original.txt (stat -c %h), then delete original.txt. Show that hard.txt still reads fine, report whether soft.txt still works ([[ -e ... ]] follows the link), and print where the symlink points with readlink.

Hint: a hard link is another name for the same inode, so the data lives on until the last name is removed.

Bash Exercise 4: Hard links and symbolic links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
ln original.txt hard.txt
ln -s original.txt soft.txt
echo "v2" >> soft.txt
echo "links: $(stat -c %h original.txt)"
rm original.txt
echo "hard link still reads:"
cat hard.txt
[[ -e soft.txt ]] && echo "soft link works" || echo "soft link is dangling"
readlink soft.txt

The link count is 2 because original.txt and hard.txt are two names for one inode. Appending through soft.txt writes to the target. After rm original.txt the data is still reachable through hard.txt, but the symbolic link only stores the name original.txt, so it dangles.

5. Find by size and by time (Intermediate)

The directory logs has several files with fixed sizes and modification times, and ref is a reference file. Print (sorted) the .log files that are larger than 100 bytes, then print (sorted) all regular files newer than ref.

Hint: find -size +100c counts bytes with the c suffix; -newer FILE compares modification times.

Bash Exercise 5: Find by size and by time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
find logs -name '*.log' -size +100c | sort
echo "--- newer than ref"
find logs -type f -newer ref | sort

Without the c suffix -size counts 512-byte blocks and rounds up, which surprises people. The pattern '*.log' is quoted so that the shell does not expand it before find sees it.

Reading and searching text

These problems use wc, head and tail, grep, sort and uniq and the Input box with reading input.

6. Count, sum and maximum from the Input box (Beginner)

The numbers in the Input box (one per line) arrive on standard input. Print three lines: count: N, sum: S and max: M.

Hint: awk reads standard input when no file is given. NR is the number of lines read so far.

Bash Exercise 6: Count, sum and maximum from the Input box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
awk 'NR == 1 || $1 > max { max = $1 } { sum += $1 } END { print "count: " NR; print "sum: " sum; print "max: " max }'

For the first line (NR == 1) and whenever a number beats the current maximum, max is updated; sum accumulates every line; the END block runs after the input ends. A sort -n | tail -n 1 pipeline would also find the maximum, but awk does all three jobs in one pass.

7. Lines from the middle and the end (Beginner)

numbered.txt contains line 1 to line 10. Print lines 3 to 5, then the last two lines.

Hint: sed -n '3,5p' prints a range only, and tail -n 2 prints the end.

Bash Exercise 7: Lines from the middle and the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
sed -n '3,5p' numbered.txt
echo "..."
tail -n 2 numbered.txt

-n turns off sed's automatic printing, so only the lines selected by 3,5p appear. head -n 5 numbered.txt | tail -n 3 is another valid way to get the same lines.

8. Searching a log with grep (Beginner)

app.log contains log lines. Print: the number of lines that contain ERROR (upper case only); every line containing WARN with its line number; and the number of lines that do not contain INFO.

Hint: -c counts, -n numbers the lines, -v inverts the match.

Bash Exercise 8: Searching a log with grep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
echo "errors: $(grep -c ERROR app.log)"
grep -n WARN app.log
echo "not INFO: $(grep -vc INFO app.log)"

grep is case-sensitive by default, so the lowercase error: line is not counted; add -i to count it. -vc combines invert and count: five lines remain after removing the three INFO lines.

9. The three most common words (Intermediate)

Print the three most frequent words in text.txt as COUNT WORD, ignoring case and punctuation. When counts tie, list the words alphabetically.

Hint: turn letters to lower case with tr, split into one word per line with tr -cs, then sort | uniq -c and a second sort.

Bash Exercise 9: The three most common words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
tr 'A-Z' 'a-z' < text.txt |
  tr -cs 'a-z' '\n' |
  sort | uniq -c |
  sort -k1,1nr -k2 |
  head -n 3

tr -cs 'a-z' '\n' replaces every run of characters that are not lower-case letters (-c complements, -s squeezes repeats) with one newline, which leaves one word per line. After sort | uniq -c, the final sort -k1,1nr -k2 orders by count descending, then by word.

10. Columns with cut and tr (Intermediate)

people.csv has a header line. Skip the header and print each person's name and city in upper case, separated by a tab.

Hint: tail -n +2 starts printing at line 2. In tr, '\t' stands for a tab.

Bash Exercise 10: Columns with cut and tr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
tail -n +2 people.csv | cut -d, -f1,3 | tr ',a-z' '\tA-Z'

cut -d, -f1,3 keeps the first and third comma-separated fields. tr ',a-z' '\tA-Z' maps the comma to a tab and each lower-case letter to its upper-case partner in one pass, because the two sets are matched position by position.

Editing, reporting, redirection and archives

The last group combines sed, awk, redirection, archives and pipelines.

11. Edit a config file with sed (Intermediate)

Using sed -i.bak in a single command, change debug=true to debug=false in app.conf and delete all comment lines (lines starting with #). Print the new file, then show what changed by comparing app.conf.bak with app.conf using diff (add || true, because diff exits with 1 when the files differ).

Hint: give sed two -e expressions. -i.bak keeps the original as app.conf.bak.

Bash Exercise 11: Edit a config file with sed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
sed -i.bak -e 's/^debug=true$/debug=false/' -e '/^#/d' app.conf
cat app.conf
echo "--- diff"
diff app.conf.bak app.conf || true

s/^debug=true$/debug=false/ is anchored at both ends so it only changes that exact line. /^#/d deletes the lines whose first character is #. The .bak copy lets you undo the edit. -i is GNU sed syntax; on macOS the option takes a separate argument (-i '').

12. Totals per category with awk (Intermediate)

sales.csv has lines like food,12.50. Print the total per category as NAME TOTAL with the name left-aligned in 6 columns and the total with two decimals right-aligned in 7 columns, largest total first.

Hint: an awk associative array sums by key; use printf for the format and a final sort -k2,2nr.

Bash Exercise 12: Totals per category with awk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
awk -F, '{ total[$1] += $2 } END { for (name in total) printf "%-6s %7.2f\n", name, total[name] }' sales.csv |
  sort -k2,2nr

for (name in total) visits the keys in no particular order, so the pipeline sorts afterwards: key 2, numeric, reversed. The format %-6s %7.2f pads the name to 6 characters and prints the number in a field 7 wide with two decimals.

13. Separating stdout and stderr (Intermediate)

The function noisy prints three lines to standard output and three to standard error. Run it so that stdout goes to out.txt and stderr to err.txt. Run it a second time, appending its stderr to err.txt and discarding stdout. Print the line counts of both files. Finally, run it once more with both streams in one file both.txt and show the first four lines of that file.

Hint: >> appends, 2>> appends stderr, and > file 2>&1 sends both streams to the same place.

Bash Exercise 13: Separating stdout and stderr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
noisy > out.txt 2> err.txt
noisy 2>> err.txt > /dev/null
echo "out.txt: $(wc -l < out.txt) lines, err.txt: $(wc -l < err.txt) lines"
noisy > both.txt 2>&1
head -n 4 both.txt

The second run contributes three more lines to err.txt (6 in total) and nothing to out.txt (still 3). In > both.txt 2>&1 the order matters: stdout is redirected first and stderr then follows it. The result keeps the lines in the order they were written.

14. Archive, restore and verify (Advanced)

Create project.tar.gz from the directory project, excluding *.tmp files. Print the archive's contents in sorted order. Extract it into a new directory restore, then verify the restore with diff -r (telling it to ignore *.tmp files, because the original still has one) and print restore matches when they are identical.

Hint: tar --exclude='*.tmp' -czf ...; list with -tzf; extract with -xzf ... -C restore.

Bash Exercise 14: Archive, restore and verify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
tar --exclude='*.tmp' -czf project.tar.gz project
tar -tzf project.tar.gz | sort
mkdir restore
tar -xzf project.tar.gz -C restore
diff -r --exclude='*.tmp' project restore/project && echo "restore matches"

The quotes around *.tmp keep the shell from expanding it, so tar receives the pattern. -C restore changes into that directory before extracting. diff -r compares two trees recursively and exits with 0 only when they are identical, which is what makes the && work.

15. Pipeline: who causes the 404s? (Advanced)

Each line of access.log has the form IP STATUS PATH. Print the two IP addresses with the most 404 responses as COUNT IP, the biggest first. Break ties by IP address.

Hint: filter with awk, then the classic sort | uniq -c | sort -nr frequency table, then head.

Bash Exercise 15: Pipeline: who causes the 404s?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Show solution
Terminal
awk '$2 == 404 { print $1 }' access.log |
  sort | uniq -c |
  sort -k1,1nr -k2 |
  head -n 2

awk '$2 == 404 { print $1 }' keeps only the IP column of the 404 lines. uniq -c only counts adjacent duplicates, which is why sort must come first. The second sort puts big counts first and uses the IP as a tie-breaker, which makes the output deterministic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the word-frequency problem, why must sort come before uniq -c?

    uniq compares each line only with the previous one. Sorting brings equal lines together, which is why sort | uniq -c is the standard frequency idiom.
  2. 2. What does ( umask 077; touch new.txt ) achieve compared with running the two commands unparenthesized?

    A subshell is a child process, and changes to its umask, variables or directory vanish when it ends.
  3. 3. Why does noisy > both.txt 2>&1 work but noisy 2>&1 > both.txt send stderr to the terminal?

    In the second form stderr is attached to the terminal copy of stdout first, and only then is stdout redirected to the file.
  4. 4. A symbolic link and a hard link both point at original.txt, and you delete original.txt. What happens?

    The data is freed when the last hard link goes away. A symbolic link stores a path, and a path to a deleted name leads nowhere.
  5. 5. What is the effect of quoting the pattern in find logs -name '*.log'?

    Without quotes the shell may expand *.log against the current directory first. Quoted, find receives the literal pattern and applies it to every name it visits.

Summary

  • Brace expansion, loops over globs and ${f%.ext} solve most bulk-renaming jobs without extra tools.
  • Permissions are sums of 4, 2 and 1; the umask is subtracted from the default mode; a subshell keeps a umask change local.
  • A hard link is another name for an inode; a symbolic link is a stored path and can dangle.
  • find can filter by size (+100c), time (-newer) and name (quoted patterns).
  • tr, cut, sort | uniq -c | sort -nr and awk handle most text-summary jobs in a few stages; sort first, and break ties explicitly to keep output stable.
  • Redirections are read left to right; >> appends and 2>> appends stderr.

Next: Practice Problems: Scripting and Pipelines