Skip to content

Click on each book below to review & buy on Amazon.

As an Amazon Associate, I earn from qualifying purchases.


LPI Linux Essentials Exam 010-160 - Topic 3.3 - Create & Execute a Shell Script

A shell script is a computer program that contains a series of commands written in a shell scripting language, such as Bash (Bourne Again SHell). It is designed to be executed by a shell interpreter. Shell scripts provide a convenient and powerful way to automate tasks and execute complex operations by combining multiple commands into a single script.

Shell scripts can perform a wide range of functions, from simple tasks like file manipulation and system administration to more complex operations like process management and network programming. They can interact with the operating system, execute system commands, manipulate files and directories, control program flow with conditionals and loops, and handle user input and output.

One of the primary advantages of shell scripting is its flexibility and portability across different Unix-like systems. Shell scripts are interpreted rather than compiled, allowing for easy modification and quick testing. They can also be used as a scripting language for system administration, automating repetitive tasks, and creating customized solutions.

Interpreters

There are several shell interpreters available that can execute shell scripts. Here are some commonly used ones:

  • bash (Bourne Again SHell): Bash is one of the most popular and widely used shell interpreters. It is the default shell on most Linux distributions.
  • sh (Bourne Shell): Bourne Shell was one of the original Unix shells and serves as the basis for many other shells. It is available on most Unix-like systems.
  • csh (C Shell): C Shell is a shell with a syntax resembling the C programming language. It offers additional features like command-line editing and history. It is commonly found on BSD-based systems.
  • ksh (Korn Shell): Korn Shell: The Korn Shell (ksh) is a powerful and versatile shell that incorporates features from the Bourne shell (sh) and the C shell (csh). It offers advanced scripting capabilities, command-line editing, and programmable command-line completion.
  • tcsh (TENEX C Shell): TENEX C Shell is an extended version of C Shell that incorporates additional features and improvements. It is known for its interactive command-line editing capabilities.
  • zsh (Z Shell): Zsh is an extended shell that includes features from various shells, including Bash, Korn Shell, and C shell. It provides advanced command-line editing, powerful scripting capabilities, and extensive customization options.

These are just a few examples of shell interpreters, and there are others available as well. The choice of shell interpreter depends on the specific requirements and preferences of the user or system administrator.

shebang / shabang / hashbang

The shebang tells the system which interpreter should be used to execute the script. In the case of a bash script, the shebang is typically written as:

#!/bin/bash

Let's break down the shebang line:

  • The first two characters, #!, indicate to the system that this is a shebang line.
  • Following the shebang indicator is the path to the interpreter, in this case, /bin/bash. It specifies the location of the Bash interpreter executable on the system.
  • After the interpreter's path, any additional arguments or options can be provided. For example, #!/bin/bash -e would start the script with the -e option, which causes the script to exit immediately if any command within it fails.

When you run a script with a shebang line, the system looks at the specified interpreter, such as /bin/bash, and passes the script file to that interpreter for execution. This allows you to write scripts in different programming languages and have them automatically executed by the appropriate interpreter.

The shebang line must be the very first line in the script file and should not be preceded by any whitespace or comments. However, the shebang line is optional. If a script does not have a shebang line, it can still be executed by explicitly passing it to the appropriate interpreter (e.g., bash script.sh).

Using the shebang line allows you to make your scripts more portable and executable with a simple command, such as ./script.sh, instead of explicitly specifying the interpreter every time.

The PATH Environment Variable

Understanding the PATH environment variable is essential for running shell scripts and commands in Linux. The PATH variable contains a colon-separated list of directories that the shell searches through when you enter a command. When a command is issued in the shell, it checks each directory listed in the PATH variable in the order they are listed. If the shell finds a matching executable in one of the directories, it runs the program. Otherwise, it returns an error indicating that the command is not found.

When executing a shell script, if you place its location within a directory that's part of the PATH, you won’t need to type the script’s full path to execute it. Instead, typing the script’s name suffices. Conversely, if the script is not within a directory listed in the PATH, you must provide the full path or navigate to the directory containing the script to run it.

The current value of the PATH variable can be displayed using the command echo $PATH. To add a new directory to the PATH variable, you could use the export command as follows:

export PATH=$PATH:/path/to/directory

This command appends :/path/to/directory to the existing PATH. It is temporary and only affects the current session. To make this change permanent, you would add the export command to your profile script (.bash_profile, .profile, or .bashrc), which gets executed whenever you open a new shell session.

When executing scripts from the current directory, a common practice is to prefix the script name with ./, indicating that the shell should look in the current directory:

./my_script.sh

Execute Permission

In Linux and other Unix-like operating systems, files need to have execute permission to be run as scripts. File permissions determine who can read, write, or execute the file. When a shell script is created, it does not have execute permission by default. To allow the script to be executed, you must set the execute permission bit using the chmod (change mode) command.

To add execute permissions for the owner of the file, you would use the following command:

chmod u+x script.sh

The u+x argument tells chmod to add (+) execute (x) permissions for the user/owner (u) of the file. Similarly, to add execute permissions for the group and others, you would use g+x and o+x, respectively. To add execute permission for all (user, group, and others), you can use:

chmod a+x script.sh

Once the execute permission is set, you can run the script by typing its path in the command line, as mentioned earlier with the ./script.sh notation if you are in the same directory as the script.

Create and Run a Simple Shell Script

To create and run a shell script you first need to create a file with the appropriate extension, such as .sh. This is not required in Linux as file extensions do not mean anything, however it makes readability for everyone that much better.

After creating the file, it will need the interpreter and commands adding that you want to run, with the file being made executable.

"Exercise: Creating & running a simple shell script:

Create a suitable directory for the script:

mkdir -p ~/scripts

Change into scripts directory:

cd scripts

Create a script to perform a simple calculation:

cat << 'EOF' > calc.sh
#!/bin/bash

# This is a basic shell script demo
# It performs a simple calculation and displays the result

num1=3
num2=5

result=$(( num1 + num2 ))

echo "The result of the calculation is: $result"

EOF

Give the script execute permissions:

chmod -v u+x calc.sh

Execute the script:

./calc.sh 

The script should print to screen:

The result of the calculation is: 8

Support DTV Linux

Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.

NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.