Getting ready
Commands are typed and executed in a terminal session. When a terminal is opened, a prompt is displayed. The prompt can be configured in many ways, but frequently resembles this:
username@hostname$
Alternatively, it can also be configured as root@hostname # or simply as $ or #.
The $ character represents regular users and # represents the administrative user root. Root is the most privileged user in a Linux system.
A shell script typically begins with a shebang:
#!/bin/bash
Shebang is a line on which #! is prefixed to the interpreter path. /bin/bash is the interpreter command path for Bash. A line starting with a # symbol is treated by the bash interpreter as a comment. Only the first line of a script can have a shebang to define the interpreter to be used to evaluate the script.
A script can be executed in two ways:
- Pass the name of the script as a command-line argument:
bash myScript.sh
- Set the execution permission on a script file to make it executable:
chmod 755 myScript.sh ./myScript.sh.
If a script is run as a command-line argument for bash, the shebang is not required. The shebang facilitates running the script on its own. Executable scripts use the interpreter path that follows the shebang to interpret a script.
Scripts are made executable with the chmod command:
$ chmod a+x sample.sh
This command makes a script executable by all users. The script can be executed as follows:
$ ./sample.sh #./ represents the current directory
Alternatively, the script can be executed like this:
$ /home/path/sample.sh # Full path of the script is used
The kernel will read the first line and see that the shebang is #!/bin/bash. It will identify /bin/bash and execute the script as follows:
$ /bin/bash sample.sh
When an interactive shell starts, it executes a set of commands to initialize settings, such as the prompt text, colors, and so on. These commands are read from a shell script at ~/.bashrc (or ~/.bash_profile for login shells), located in the home directory of the user. The Bash shell maintains a history of commands run by the user in the ~/.bash_history file.
This is equivalent to these:
$ cmd1
$ cmd2
A comment starts with # and proceeds up to the end of the line. The comment lines are most often used to describe the code, or to disable execution of a line of code during debugging:
# sample.sh - echoes "hello world" echo "hello world"
Now let's move on to the basic recipes in this chapter.