TExcelTAD
Home › Terminal & Command Line › Terminal Exercises

Terminal Exercises

Time to practise across all the shells. Each exercise names its shell and has a starter playground that already runs and prints a placeholder, so you can see the format. Replace the TODO parts, press ▶ Run and compare with the "Expected" lines. The solutions are runnable too, but try for a few minutes first: that's where the learning happens.

Every playground starts in an empty folder, so each one creates the files it needs.

# Exercise Shell Topics
1 Project skeleton bash mkdir -p, touch, find
2 The same skeleton in CMD CMD mkdir, echo >, dir /b /o:n
3 Files per extension PowerShell Get-ChildItem, Group-Object
4 Back up only if it exists bash &&, ||, cp
5 A greeting with a default CMD call :label, %~1, if
6 Count the errors PowerShell Select-String, pipeline
7 Orders per customer bash cut, sort, uniq -c, awk
8 Arguments and quoting zsh script file, shebang, chmod +x, $@
9 Fix Windows line endings bash CRLF, grep -c, sed
10 Batch rename CMD ren with wildcards

1. Project skeleton (bash)

Create this structure with as few commands as possible: a folder app containing src, tests and docs, an empty app/src/main.py, and app/README.md containing the line # app. Then print every path, sorted.

Expected:

text
app
app/README.md
app/docs
app/src
app/src/main.py
app/tests
bash · try it yourself
# TODO: create the folders and files
mkdir app
find app | sort
app
Show solution
bash · try it yourself
mkdir -p app/src app/tests app/docs
touch app/src/main.py
echo "# app" > app/README.md
find app | sort
app
app/README.md
app/docs
app/src
app/src/main.py
app/tests

mkdir -p creates parent folders as needed and accepts several paths at once. In bash you can shorten the first line further with brace expansion: mkdir -p app/{src,tests,docs}.

2. The same skeleton in CMD

Build the same structure in a batch file and list the contents of app and app\src in name order.

Expected:

text
docs
README.md
src
tests
---
main.py
cmd · try it yourself
@echo off
rem TODO: create the folders and files
mkdir app
dir /b /o:n app
echo ---
---
Show solution
cmd · try it yourself
@echo off
mkdir app\src app\tests app\docs
type nul > app\src\main.py
echo # app> app\README.md
dir /b /o:n app
echo ---
dir /b /o:n app\src
docs
README.md
src
tests
---
main.py

CMD's mkdir creates missing parent folders automatically (like mkdir -p), and type nul > file is the batch way to create an empty file. Note that the sort is case-insensitive: docs comes before README.md.

3. Files per extension (PowerShell)

Count the files in reports by extension and print one line per extension, alphabetically, in the form .ext: count.

Expected:

text
.csv: 3
.md: 1
.txt: 2
powershell · try it yourself
New-Item -ItemType Directory reports | Out-Null
'jan.csv', 'feb.csv', 'mar.csv', 'notes.txt', 'todo.txt', 'README.md' |
    ForEach-Object { New-Item -Path reports -Name $_ | Out-Null }
# TODO: group the files by extension
$files = Get-ChildItem reports -File
"$($files.Count) files"
6 files
Show solution
powershell · try it yourself
New-Item -ItemType Directory reports | Out-Null
'jan.csv', 'feb.csv', 'mar.csv', 'notes.txt', 'todo.txt', 'README.md' |
    ForEach-Object { New-Item -Path reports -Name $_ | Out-Null }
Get-ChildItem reports -File |
    Group-Object Extension |
    Sort-Object Name |
    ForEach-Object { "$($_.Name): $($_.Count)" }
.csv: 3
.md: 1
.txt: 2

Group-Object makes one group per distinct value of the property; each group has a Name and a Count. The bash version of this task is ls reports | sed 's/.*\./. /' | sort | uniq -c.

4. Back up only if it exists (bash)

Write a function backup that copies a file into backup/ only if the file exists, printing backed up NAME on success and skipped NAME otherwise. Use && and || instead of if. Then list the backup folder.

Expected:

text
backed up app.cfg
skipped db.cfg
backed up users.cfg
app.cfg
users.cfg
bash · try it yourself
echo "port=8080" > app.cfg
echo "admin=ada" > users.cfg
mkdir -p backup
backup() {
  echo "TODO $1"
}
backup app.cfg
backup db.cfg
backup users.cfg
ls backup
TODO app.cfg
TODO db.cfg
TODO users.cfg
Show solution
bash · try it yourself
echo "port=8080" > app.cfg
echo "admin=ada" > users.cfg
mkdir -p backup
backup() {
  [ -f "$1" ] && cp "$1" backup/ && echo "backed up $1" || echo "skipped $1"
}
backup app.cfg
backup db.cfg
backup users.cfg
ls backup
backed up app.cfg
skipped db.cfg
backed up users.cfg
app.cfg
users.cfg

The chain stops at the first failing command: if [ -f ... ] fails, cp and the first echo are skipped and || runs. In CMD the same idea is if exist "%~1" (copy "%~1" backup\ >nul && echo backed up %~1) else echo skipped %~1.

5. A greeting with a default (CMD)

Write a subroutine :greet that prints Hello, NAME!, using World when no name is passed. Call it three times: with no argument, with Ada, and with "Grace Hopper" (in quotes, since it contains a space).

Expected:

text
Hello, World!
Hello, Ada!
Hello, Grace Hopper!
cmd · try it yourself
@echo off
call :greet
call :greet Ada
call :greet "Grace Hopper"
exit /b

:greet
rem TODO: use %~1, with World as the default
echo Hello, %1!
exit /b
Hello, !
Hello, Ada!
Hello, "Grace Hopper"!
Show solution
cmd · try it yourself
@echo off
call :greet
call :greet Ada
call :greet "Grace Hopper"
exit /b

:greet
set "name=%~1"
if not defined name set "name=World"
echo Hello, %name%!
exit /b
Hello, World!
Hello, Ada!
Hello, Grace Hopper!

%~1 removes the surrounding quotes; %1 keeps them. set "name=%~1" with an empty argument removes the variable, so if not defined detects it. The first exit /b stops the main part from falling through into the subroutine.

6. Count the errors (PowerShell)

From app.log, print how many lines contain ERROR, then each distinct error message (the text after ERROR ) once, sorted.

Expected:

text
4 errors
disk full
timeout
user not found
powershell · try it yourself
@'
10:01 INFO start
10:02 ERROR timeout
10:03 WARN slow
10:04 ERROR disk full
10:05 INFO retry
10:06 ERROR timeout
10:07 ERROR user not found
'@ | Set-Content app.log
# TODO: find the ERROR lines and their messages
"? errors"
? errors
Show solution
powershell · try it yourself
@'
10:01 INFO start
10:02 ERROR timeout
10:03 WARN slow
10:04 ERROR disk full
10:05 INFO retry
10:06 ERROR timeout
10:07 ERROR user not found
'@ | Set-Content app.log
$errors = Select-String -Path app.log -Pattern 'ERROR (.+)
  

 -CaseSensitive
"$($errors.Count) errors"
$errors | ForEach-Object { $_.Matches[0].Groups[1].Value } | Sort-Object -Unique
4 errors
disk full
timeout
user not found

The capture group (.+) holds the message. In bash: grep -c ERROR app.log for the count and grep -o 'ERROR .*' app.log | cut -d' ' -f2- | sort -u for the messages.

7. Orders per customer (bash)

orders.csv has the columns id,customer,amount. Print each customer with their number of orders, most orders first, as customer count.

Expected:

text
ada 3
bob 2
cy 1
bash · try it yourself
cat > orders.csv <<'CSV'
id,customer,amount
1,ada,20
2,bob,15
3,ada,7
4,cy,30
5,bob,12
6,ada,9
CSV
# TODO: skip the header, take column 2, count and sort
tail -n +2 orders.csv | wc -l
6
Show solution
bash · try it yourself
cat > orders.csv <<'CSV'
id,customer,amount
1,ada,20
2,bob,15
3,ada,7
4,cy,30
5,bob,12
6,ada,9
CSV
tail -n +2 orders.csv | cut -d, -f2 | sort | uniq -c | sort -rn | awk '{ print $2, $1 }'
ada 3
bob 2
cy 1

uniq -c only merges adjacent duplicates, which is why sort comes first. In PowerShell: Import-Csv orders.csv | Group-Object customer | Sort-Object Count -Descending | ForEach-Object { "$($_.Name) $($_.Count)" }.

8. Arguments and quoting (zsh)

Write a script file args.zsh that prints how many arguments it got, then each argument numbered. Make it executable and run it as ./args.zsh red "green blue".

Expected:

text
2 arguments
1: red
2: green blue
zsh · try it yourself
cat > args.zsh <<'EOF'
#!/usr/bin/env zsh
print "TODO"
EOF
# TODO: make it executable and run it with two arguments
zsh args.zsh red "green blue"
TODO
Show solution
zsh · try it yourself
cat > args.zsh <<'EOF'
#!/usr/bin/env zsh
print "$# arguments"
i=1
for arg in "$@"; do
  print "$i: $arg"
  (( i++ ))
done
EOF
chmod +x args.zsh
./args.zsh red "green blue"
2 arguments
1: red
2: green blue

The quotes on the command line make green blue one argument, and "$@" (quoted!) keeps each argument intact inside the script. Without the quotes you'd get 3 arguments.

9. Fix Windows line endings (bash)

deploy.sh was saved on Windows with CRLF line endings. Print how many lines contain a carriage return, remove them, print the count again, and run the script.

Expected:

text
CR lines before: 3
CR lines after: 0
deploying v2
bash · try it yourself
printf '#!/bin/bash\r\nversion=v2\r\necho "deploying $version"\r\n' > deploy.sh
# TODO: count, fix, count again, run
echo "CR lines before: ?"
CR lines before: ?
Show solution
bash · try it yourself
printf '#!/bin/bash\r\nversion=v2\r\necho "deploying $version"\r\n' > deploy.sh
echo "CR lines before: $(grep -c 
  

\r' deploy.sh)"
sed -i 's/\r$//' deploy.sh
echo "CR lines after: $(grep -c 
  

\r' deploy.sh)"
bash deploy.sh
CR lines before: 3
CR lines after: 0
deploying v2

#39;\r' is bash syntax for a carriage-return character. On a machine with the tool installed, dos2unix deploy.sh does the same as the sed command. See Cross-Platform Scripts.

10. Batch rename (CMD)

Rename every .txt file in drafts to .bak with one command, then list the folder.

Expected:

text
feb.bak
jan.bak
mar.bak
notes.md
cmd · try it yourself
@echo off
mkdir drafts
cd drafts
echo february> feb.txt
echo january> jan.txt
echo march> mar.txt
echo notes> notes.md
rem TODO: rename all .txt files to .bak
dir /b /o:n
feb.txt
jan.txt
mar.txt
notes.md
Show solution
cmd · try it yourself
@echo off
mkdir drafts
cd drafts
echo february> feb.txt
echo january> jan.txt
echo march> mar.txt
echo notes> notes.md
ren *.txt *.bak
dir /b /o:n
feb.bak
jan.bak
mar.bak
notes.md

ren with wildcards keeps the * part of each name and swaps the extension. PowerShell: Get-ChildItem *.txt | Rename-Item -NewName { $_.BaseName + '.bak' }. bash has no single built-in command for this: for f in *.txt; do mv "$f" "${f%.txt}.bak"; done.

Test yourself

Why does sort come before uniq -c in a counting pipeline?

  1. uniq needs numbers
  2. uniq only merges adjacent duplicate lines
  3. sort removes the header
  4. It's faster

In a batch subroutine, what is the difference between %1 and %~1?

  1. None
  2. %~1 removes surrounding quotes
  3. %~1 is the script name
  4. %~1 is the last argument

./args.zsh red green blue (no quotes) is run. How many arguments does the script receive?

  1. 1
  2. 2
  3. 3
  4. 4