Lesson 11.1: Your first script
What a shell script is and why admins write them, the shebang line and comments, writing a script in nano, why ./script says Permission denied until you chmod +x it, running it with bash instead, why the ./ is needed (PATH), installing it in ~/bin, exit codes in $? and watching a script run line by line with bash -x.
17 min
You will learn to
- Explain what a script is and when to write one
- Write a script with a shebang and comments
- Make it executable with chmod +x and run it with ./
- Explain why a script in the current directory needs ./
- Read a command's exit status in $?
- Trace a script with bash -x
Key terms
- Script
- A text file containing commands that a program (here the bash shell) reads and runs from top to bottom.
- Interpreter
- A program that reads a script and carries out its instructions one by one, without turning it into machine code first.
- Shebang (#!)
- The first line of a script, #! followed by the interpreter's path. The kernel reads it and starts that interpreter with the script.
- Comment
- Text the shell ignores: everything after a #. It explains the script to the next reader, often you in six months.
- Execute permission (x)
- The permission bit that lets a file be run as a program (lesson 4.3). Set with chmod +x.
- Exit status
- A number from 0 to 255 every command returns when it ends. 0 means success, anything else a kind of failure. The shell keeps the last one in $?.
← Cleaning data with regular expressions in sed and awk · All lessons · Variables, arguments and input →