Master

A script that runs anywhere

A script that works in the folder where you wrote it is not finished. The next person runs it from elsewhere, on a different day, with different files present. Making a script location independent is the step that turns a command you remember into a tool you can hand over.

What you will see

The same folder both times - the script does not depend on where you stand, which is the point of this lesson.

About 2 min of reading

Try It

Make a script location independent.

1

Write it

printf '#!/bin/sh\nhere=$(printf %%s ./%%s | awk "{print \$1}")\n[ -d "$here" ] || { echo "no folder"; exit 1; }\necho working in %s\n' > loc.sh

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

What it prints
A script that reports the folder it resolved.
2

Run it from two places

chmod +x loc.sh && ./loc.sh && cd .. && ./tmp/loc.sh

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

What it prints
The same folder both times - the script does not depend on where you stand, which is the point of this lesson.

Data Flow

Setup, work, then a single move.
1 Resolve the script's own location
↓
2 Check arguments and options
↓
3 Do the work in a temporary folder
↓
4 Move the result into place
Why this works
Set the state at the top

Resolve paths, check arguments, and set the options that make it stop on failure, all before any work begins. A script whose setup is visible in the first ten lines can be reviewed without running it.

Write to a temporary place then move

Build the output in a temporary folder and move it into place at the end. If the run fails halfway, the previous good output is still there, which is the difference between a broken deploy and a half written one.

Examples

Work from the script's own folder

Take the directory the script lives in rather than the directory you are standing in. Then the paths inside it are the same whether you ran it from the terminal, from another folder, or from a build tool.

Arguments over assumptions

Take the input path as an argument with a default, and check it exists. A script that assumes a filename will be there fails silently the month the file is renamed.

Refuse to run in the wrong place

If a script writes into a folder, confirm the folder is the one it expects before writing. One check at the top prevents the run that put a hundred files in the wrong directory.

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.

← Environment variables
Previous Lesson
Environment variables
Next Lesson
Debugging a shell script
Debugging a shell script →