NUnix · L3 MIAGE · CM3 · 90 minutes
ISTIC · University of Rennes
2026–2027
A support team has several log files. We will build a script that counts matching lines and saves a report.
How can a script use a filename we type or pass as an argument?
A script uses these parameters to read its arguments:
| Parameter | Meaning | Value for this call |
|---|---|---|
$0 |
Script name | arguments.sh |
$1 |
First argument | L3 MIAGE |
$2 |
Second argument | Unix |
$# |
Number of arguments | 2 |
"$@" |
All arguments separately | "L3 MIAGE" "Unix" |
"$*" |
All arguments as one string | "L3 MIAGE Unix" |
Use the same script call:
Inside the script, printf uses %s for a string and \n for a newline.
It repeats the format for each argument.
Use "$@" to pass each argument on unchanged.
-c tells Bash to execute the following text as commands.bash script.sh reads commands from a file.
bash -c 'commands' reads them from the next argument.
export includes it in the environment passed to newly started programs.A child receives a copy. Changing it does not change the parent's variable.
Before reading a file, how can a script check that it exists and is readable?
Compare integers with these operators inside [ ... ]:
| Operator | Read it as | Mathematical symbol |
|---|---|---|
-eq |
Equal to | = |
-ne |
Not equal to | ≠ |
-lt |
Less than | < |
-le |
Less than or equal to | ≤ |
-gt |
Greater than | > |
-ge |
Greater than or equal to | ≥ |
Read [ "$count" -gt 10 ] as count is greater than 10.
An interactive script can stop when the user types end.
| Test | True when... |
|---|---|
[ "$answer" = "end" ] |
The answer is end |
[ "$answer" != "end" ] |
The answer is different from end |
[ -z "$answer" ] |
The answer is empty |
[ -n "$answer" ] |
The answer is not empty |
Use = for text and -eq for integer comparisons.
A script can check a path before using it:
| Test | True when... |
|---|---|
[ -e "$filename" ] |
The path exists |
[ -f "$filename" ] |
It is a regular file |
[ -d "$filename" ] |
It is a directory |
[ -r "$filename" ] |
Reading is allowed |
[ -w "$filename" ] |
Writing is allowed |
[ -x "$filename" ] |
Executing / directory traversal is allowed |
Example call: bash check.sh report.log ERROR 10
$1 names an existing regular file.$1 starts with report.[[ ... ]] supports patterns in Bash. Keep report* unquoted.
&& means AND: stop checking as soon as one condition is false.
How can we process several files, or ask again until the user types end?
Checking i=1
Body: 1
Checking i=2
Body: 2
Checking i=3
Body: 3
Checking i=4
How can we reuse a file-processing step for several files?
Define the function, then call it with a filename:
$1 is the argument passed to this call.local gives the function its own filename variable.Imagine we run a website and a night job. How many error lines did each produce?
Each service writes a log: a text file recording what happened.
Website: web.log
10:00 INFO STARTED
10:01 ERROR DISK_FULL
10:02 WARN SLOW_REQUEST
10:03 ERROR TIMEOUT
10:04 INFO REQUEST_OK
10:05 ERROR DISK_FULL
Night job: worker night.log
22:00 INFO STARTED
22:01 ERROR TIMEOUT
22:02 INFO JOB_DONE
22:03 WARN RETRY
22:04 ERROR QUEUE_FULL
How many lines contain ERROR in each file?
Let's write report.sh to count matching lines in each log.
It asks what to search for. We enter ERROR.
It saves this report in search-report.txt:
Matching lines for: ERROR
web.log: 3 matching lines
worker night.log: 2 matching lines
Download and extract the files.
Work in report-demo and edit report.sh.
We will add and run the script one step at a time.
First question: what should happen if no filenames are supplied?
Create search-report.txt once, before the loop:
Inside the loop, append each file's count to that report:
Why >> here? Each file's result must be added after the previous one.
After the loop: echo "Report saved in $report".
Type ERROR, then run cat search-report.txt:
Matching lines for: ERROR
web.log: 3 matching lines
worker night.log: 2 matching lines
Try WARN, FATAL, a missing file and a call with no arguments.
Complete script
read or the script's arguments.Reference for the TD/TP: extra Bash forms, worked examples and text-editing tools
Bash passes these as ordinary arguments. The script interprets them
with getopts "hp:" option, reading one option at a time:
| Item | Meaning |
|---|---|
h |
Accept -h without a value |
p: |
Accept -p with a required value |
option |
Variable receiving the option letter |
OPTARG |
Variable receiving its value, here samples |
directory="."
while getopts "hp:" option; do
case "$option" in
h) echo "Usage: $0 [-p DIRECTORY]"; exit 0 ;;
p) directory="$OPTARG" ;;
*) exit 1 ;;
esac
done
echo "Selected directory: $directory"The loop runs while another option is available.
An unknown option or a missing value reaches the *) branch.
After bash inspect.sh -p logs app.log, the script can do:
Output: logs, then app.log.
shift 2 removes the first two arguments and renumbers the remaining ones.
After getopts, OPTIND is the position of the next argument.
shift "$((OPTIND - 1))" removes the arguments it has read.
For a file containing cat cat:
Output: dog cat, then dog dog.
s/old/new/ replaces the first match on each line.g replaces every match on each line.sed -i 's/cat/dog/g' animals.txt changes the file itself.
Practise on copies.
Bash = Bourne-Again SHell.
The name puns on Stephen Bourne, author of the earlier Unix shell sh.
We use Bash syntax in this course.
sh script.sh may select a different shell with fewer features.
| Symbol | Names you may hear |
|---|---|
| # | hash, number sign; pound sign in US usage |
| # | French: croisillon, also carré |
| ♯ | The musical sharp sign (dièse) |
#!: hash followed by bang.
The symbol’s name and its role depend on context.
0: true or false?false; echo yes print?false && echo yes print?false || true?; always continues.0, from the final executed command, true.IFS= disables trimming of leading/trailing spaces for this read.-r keeps backslashes unchanged, as in the earlier prompt.read succeeds for each complete line; at EOF, it fails and the loop stops.< names.txt supplies input to the whole loop.| Command | Effect |
|---|---|
continue |
Skip the rest of the current iteration |
break |
Leave the current loop |
exit n |
End the script with status n |
After break, execution continues after the loop.
| Variable | Meaning |
|---|---|
HOME |
Home directory |
USER |
Account name, usually set at login |
PWD, OLDPWD |
Current and previous working directories |
PATH |
Colon-separated command search directories |
SHELL |
Configured login shell, not necessarily the current shell |
TERM |
Terminal type |
HOSTNAME |
Host name in Bash |
MANPATH |
Manual search path, when explicitly set |
[[ ... ]] is another form of test available in Bash.
Here, == *.txt checks whether the name ends in .txt.
With [ ... ], string equality compares literal text; this Bash form also accepts patterns.
Spaces are still required: [[ condition ]].
$((5 / 2))?n = 3 an assignment?false?-f accept every existing directory?2 (integer division).n=3.11
2
3
5
6
7
After the loop: x=7
continue skips echo.echo runs before break.| Builtin | Use |
|---|---|
cd, pwd |
Change / report the current directory |
history |
Display command history |
exec |
Replace the shell with another program |
exit |
End the current shell |
kill |
Send a signal |
trap |
Arrange a response to a signal or shell event |
| Builtin | Use |
|---|---|
declare, readonly, local |
Define variable attributes or scope |
export, set |
Manage the environment / shell settings |
echo, read |
Print output / read input |
let, test |
Arithmetic / condition tests |
shift |
Discard leading positional parameters |
return |
End a function and report its status |