← Linux and the Command Line Lesson 38 of 51 · 10 XP

Comments and the shebang

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A script is a text file with commands. The first line is special: the shebang (#!) tells the system which program should run it.

#!/bin/sh
# This is a comment: from # to the end of the line
echo "Hello"     # it can also come after a command
shebang
#!/bin/sh the POSIX shell: works everywhere (dash, BusyBox)
#!/bin/bash bash: arrays, [[ ]], ${var,,} and other conveniences
#!/usr/bin/env python3 find python3 in the PATH — the portable option

Running a script:

chmod +x script.sh      # once: allow it to run
./script.sh             # the system reads the shebang and calls the right program
sh script.sh            # or give the shell explicitly (then the shebang isn't needed)

The ./ is a must: for security reasons, the current folder isn't in the PATH.

Inside a script, $0 is the script's name, $1, $2… are the arguments, $# is how many there are, and "$@" is all the arguments, each one separately.

A good practice is to write set -eu at the start of a bash script: -e stops the script at the first error, and -u when an undefined variable is used.

Task. Write a script with the shebang #!/bin/sh and a comment about what it does. It prints the number of arguments, and then each argument on a separate line with its number: 1: first. The tests run the script with arguments.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.