Basic

Running a script

A script is a file of commands you can run again. Making one runnable is two steps: a line that says which shell reads it, and permission to execute. Both failures have clear messages, and both are worth understanding rather than working around.

What you will see

Permission denied. That message names the executable bit, not the file contents.

About 1 min of reading

Try It

Write and run a two line script.

1

Create it

printf '#!/bin/sh\necho hello from a script\n' > hi.sh && chmod +x hi.sh

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The file exists and is executable.
2

Run it

./hi.sh

Before you run it, say out loud what it will print. Then open the answer.

What it prints
hello from a script - and note the ./ that names it by path.
3

See the failure without the bit

chmod -x hi.sh && ./hi.sh

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Permission denied. That message names the executable bit, not the file contents.

Data Flow

A file becomes a program you can call.
1 Write the commands in a file
↓
2 Name the interpreter on line one
↓
3 Make the file executable
↓
4 Call it by path
Why this works
One script, one job

A script that does one thing and can be run again is worth writing the moment you do it twice. The file is the record of what you did, which is also what makes it reviewable next month.

Print what it will do

Echo each command before running it, or run with a flag that only prints. A script that says what it is about to do can be reviewed before it changes anything, which is the cheapest safety there is.

Examples

The shebang names the interpreter

#!/bin/sh on the first line tells the shell which program reads the file. Without it, the file runs in whatever shell you happen to be using, which is a different language in places.

chmod +x makes it executable

Permission denied on a file that exists means it is not executable. chmod +x script.sh fixes it. The alternative, sh script.sh, names the interpreter directly and works without the bit.

The file's own directory matters

Running ./script.sh uses the current directory, so it works from anywhere and never depends on a setting. A bare script.sh needs the file on a search path, which is a different and less obvious mechanism.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Wildcards
Previous Lesson
Wildcards
Next Lesson
Variables and quoting
Variables and quoting →