Run a script

Lesson 17 of 30 · Working with Linux

A shell script is a text file containing commands for a shell interpreter. In a new empty disposable directory, create one whose contents we know:

printf '%s\n' '#!/bin/sh' 'printf "Script started\n"' > hello.sh
cat hello.sh
sh hello.sh

The cat output shows two lines: #!/bin/sh and printf "Script started\n". The last command starts sh explicitly with the file as an argument and prints Script started. The interpreter needs to read the file; the file itself need not have execute permission for this form. The .sh suffix is a convention for people, not what chooses the interpreter.

chmod u+x hello.sh
./hello.sh

The result is again Script started. Here chmod adds execute permission for the owner, and ./ specifies the file in the current directory. For direct execution, Linux reads the first-line shebang, #!/bin/sh, and invokes the named interpreter. That interpreter must exist; filesystem mount options, directory traversal, and other restrictions may still prevent execution. A command containing / specifies a path rather than requesting the usual PATH search.

Explicit sh hello.sh chooses sh regardless of the shebang; a script requiring Bash features may fail when given to sh. Direct execution and explicit interpretation both run the script’s instructions: inspect its contents and origin before either, and do not treat an execute bit as proof of safety.