Linux Labs

Bash: text processing and scripts / Stage 4 of 9

A script is a file of commands

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 6 · on a machine · 7 min

Who reads the script

A script is an ordinary text file. It does nothing by itself: another program carries out its lines.

A script is a text file of shell commands. They are the same commands you type in the terminal, only written down in advance. They are carried out by an interpreter — a program that reads the file line by line and runs each line. For your colleague's script the interpreter is bash, the same shell that runs in your terminal.

Which program reads the file depends on how you start it. Look at the script's first line and at /bin/sh, then run the script naming the interpreter yourself.

Exercise · look

Find out who reads the script

In ~/script-lab, look at the first line of backup-notes.sh and at what /bin/sh points to, then run the script with the bash command.

First, predict

The file still has no x permission. What will bash backup-notes.sh do?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

bash backup-notes.sh names the interpreter itself: bash opens the file for reading and runs its lines. It needs no permission to run the file — the right to read it is enough.

The first line, #!/bin/bash, is the shebang: the characters #! followed by the interpreter's path. It comes into play when the file is started as a program — ./backup-notes.sh. Then the kernel reads the first line and starts the interpreter named there, handing it the file. bash file and sh file ignore that line: the interpreter is already named, and to a shell a line starting with # is a comment.

On Ubuntu, /bin/sh is a link to dash. That is a different shell — small and fast — and it knows only the syntax shared by all shells. Line 5, files=(todo.txt servers.txt), is a list; bash understands that form and dash does not, hence Syntax error: "(" unexpected. A script that starts with #!/bin/bash is run by bash — named explicitly or through the shebang.

Ubuntu 24.04
Loading…