Browse Courses

Shell Scripting Basic

An introduction to shell scripting fundamentals covering script creation execution, and the shebang directive. Learn how to write and execute simple bash scripts with practical examples.

This document introduces the fundamentals of shell scripting in Linux environments. It explains what scripts are, how they are executed, and the importance of the shebang directive. Through a step-by-step example of creating a simple "Hello World" script, readers will learn the basic workflow of writing, making executable, and running shell scripts, providing a foundation for automating tasks and developing more complex scripts.


Understanding Scripts

A script is a text file containing a sequence of commands that can be interpreted and executed by a specific program or scripting language. Scripts serve as a powerful way to automate tasks in Linux environments.

What Is a Script

At its core, a script is a list of commands that:

  • Can be run either interactively at a command line
  • Or executed sequentially from a text file
  • Are interpreted at runtime rather than being compiled
  • Are designed to automate repetitive or complex tasks

Unlike compiled programs, scripts are not converted into machine code before execution. Instead, they are processed and executed line by line at runtime by an interpreter. This makes them:

  • Easier and faster to develop
  • More portable across different systems
  • Ideal for system administration and automation tasks
  • Generally slower in execution compared to compiled programs

Common Use Cases for Scripting

Shell scripts are versatile tools that find applications in numerous areas:

Use CaseDescription
System AdministrationAutomating routine maintenance tasks, user management, and system monitoring
ETL JobsExtracting, transforming, and loading data between systems
File OperationsAutomating backups, archiving, and file system maintenance
Application IntegrationConnecting different software components and systems
Deployment AutomationStreamlining software deployment processes
Web DevelopmentCreating server-side applications and automation tools
Custom UtilitiesBuilding specialized tools for specific workflows

The flexibility of shell scripts makes them indispensable for both beginners and experienced system administrators.


The Shebang Directive

The first line of a shell script typically contains a special directive known as the “shebang” (a combination of “sharp” and “bang” for the #! characters).

Purpose and Syntax

The shebang directive tells the system which interpreter should be used to execute the script. Its syntax is:

1#!interpreter [optional-argument]

Where:

  • #! - The literal characters that mark the beginning of the shebang
  • interpreter - An absolute path to the program that should interpret the script
  • [optional-argument] - An optional string representing a single argument

Common Shebang Examples

Different scripting languages use different interpreters, which are specified in the shebang:

ShebangDescription
#!/bin/shUses the Bourne shell or a compatible shell
#!/bin/bashSpecifically uses the Bash shell
#!/bin/zshUses the Z shell
#!/usr/bin/perlInterprets the script as a Perl program
#!/usr/bin/env python3Uses the environment to locate Python 3

The shebang line is crucial because it determines how the script will be interpreted and executed.


Creating a Hello World Script

Creating a simple “Hello World” script is an excellent way to understand the basics of shell scripting. The following steps demonstrate how to create, make executable, and run a basic shell script.

Step 1: Create a Script File

First, create an empty text file with the .sh extension, which is a convention used to indicate shell scripts:

1touch hello_world.sh

Step 2: Add the Shebang Line

Add the shebang line to specify that the script should be interpreted by the Bash shell:

1echo '#!/bin/bash' > hello_world.sh

Step 3: Add Script Commands

Append the command to print “Hello World” to the script:

1echo 'echo Hello World' >> hello_world.sh

Step 4: Make the Script Executable

Before running the script, it must be made executable using the chmod command:

1chmod +x hello_world.sh

Understanding File Permissions

File permissions in Linux are divided into three categories:

PermissionSymbolMeaning
ReadrThe file can be viewed
WritewThe file can be modified
ExecutexThe file can be run as a program

To check the current permissions of a file, use:

1ls -l hello_world.sh

The output might look like:

1-rw-r--r-- 1 user group 29 Jul 3 14:45 hello_world.sh

After making the file executable with chmod +x, the permissions would change to:

1-rwxr-xr-x 1 user group 29 Jul 3 14:45 hello_world.sh

The x in the permissions indicates that the file is now executable.

Step 5: Run the Script

Now that the script is executable, it can be run:

1./hello_world.sh

This will output:

1Hello World

The ./ prefix is necessary to tell the shell to look for the script in the current directory.


Script Execution Process

When a shell script is executed, the following sequence of events occurs:

  1. The system checks if the file has execute permissions
  2. The system reads the shebang line to determine which interpreter to use
  3. The interpreter is invoked with the script file as an argument
  4. The interpreter processes the script line by line
  5. Each command in the script is executed in sequence

This process allows scripts to automate complex sequences of commands that would otherwise need to be entered manually.


Advantages and Limitations of Shell Scripts

Shell scripts offer several advantages but also come with certain limitations.

Advantages

  • Quick and easy to develop
  • No compilation step required
  • Excellent for automating system tasks
  • Leverages the power of command-line utilities
  • Easily modifiable for different scenarios

Limitations

  • Generally slower than compiled programs
  • Limited error handling capabilities
  • Can become unwieldy for complex applications
  • May have portability issues between different shells
  • Security concerns if not properly written

Understanding these trade-offs helps in deciding when shell scripting is the appropriate solution for a given task.


Conclusion

Shell scripting is a fundamental skill for Linux system administration and automation. By understanding the basics of what scripts are, how the shebang directive works, and the process of creating and executing scripts, a solid foundation is established for more advanced scripting techniques. The simple “Hello World” example demonstrates the essential workflow of creating, making executable, and running scripts that can be expanded to automate complex tasks and streamline workflows.


FAQs

A shell script is an executable text file containing a sequence of commands that are interpreted and executed by a shell program. It begins with a shebang directive that specifies which interpreter should be used, and it’s primarily used to automate tasks in Linux environments.

The shebang directive (#!/interpreter) at the beginning of a shell script tells the system which interpreter should be used to execute the script. It specifies the absolute path to the program that will interpret the commands in the script, ensuring the script is processed correctly.

Interpreted scripts differ from compiled programs in several key ways:

  • Scripts are interpreted at runtime, line by line, while compiled programs are translated to machine code before execution
  • Scripts are generally easier and faster to develop but slower to execute
  • Scripts don’t require a separate compilation step before they can be run
  • Scripts are typically more portable across different systems but may have dependencies on specific interpreters

The chmod +x filename.sh command makes a shell script executable in Linux. The chmod command changes the file mode bits, and the +x option adds execute permission for all user categories (owner, group, and others).

Common use cases for shell scripting include:

  • System administration tasks and automation
  • ETL (Extract, Transform, Load) jobs for data processing
  • File backup and archiving operations
  • Application integration between different systems
  • Deployment automation and configuration
  • Web application development (server-side)
  • Custom utilities for specific workflows

The “./” prefix when running a script (as in “./script.sh”) tells the shell to look for and execute the script in the current directory. The dot represents the current directory, and the slash is the path separator. This is necessary because, for security reasons, the current directory is typically not in the system’s PATH variable, so the shell won’t look there by default when given just the script name.

File permissions for shell scripts follow the standard Linux permission model with three categories (owner, group, others) and three permission types (read, write, execute):

  • Read (r): Allows viewing the script content
  • Write (w): Allows modifying the script
  • Execute (x): Allows running the script as a program

For a script to be executable, it must have the execute permission set, which is typically done with the command chmod +x scriptname.sh.

The sh (Bourne shell) and bash (Bourne Again SHell) differ in several ways:

  • Bash is an extended and improved version of the original Bourne shell (sh)
  • Bash includes additional features like command-line editing, command history, and programmable completion
  • Bash supports arrays, more string manipulation functions, and arithmetic operations
  • Sh is more minimalist and follows POSIX standards more strictly
  • Bash scripts may not run correctly in sh, but sh scripts typically run in bash due to backward compatibility

  1. A comment that describes what the script does
  2. A line that begins with #! followed by the path to an interpreter, telling the system which program should execute the script
  3. A command that compiles the script before execution
  4. A directive that imports external libraries into the script
(2) A shebang directive is a line at the beginning of a script that starts with #! followed by the path to an interpreter. It tells the operating system which program should be used to execute the script. For example, #!/bin/bash indicates that the Bash shell should interpret the script.

Shell scripts must be compiled before they can be executed.

False. Shell scripts are interpreted at runtime and do not require compilation. They are executed line by line by the shell interpreter specified in the shebang directive, which makes them different from compiled languages like C or C++.

The chmod +x command is used to make a shell script executable.

True. The chmod +x command adds execute permission to a file, which is necessary for a shell script to be run as a program. Without this permission, the shell would treat the script as a regular text file and would not attempt to execute its contents.

  1. The script will run but display warnings
  2. The system will automatically grant temporary execute permissions
  3. The shell will interpret the script anyway if you use the “sh” command explicitly
  4. You will receive a “Permission denied” error
(4) If you try to run a shell script without execute permissions using ./scriptname.sh, you will receive a “Permission denied” error. The operating system checks for execute permissions before attempting to run any file as a program. However, you can still execute the script by explicitly invoking a shell interpreter (like “sh scriptname.sh” or “bash scriptname.sh”), which reads the file as input rather than treating it as an executable.

  1. Shell scripts are generally faster to develop than compiled programs
  2. Shell scripts are executed line by line at runtime
  3. Shell scripts typically perform better than compiled programs
  4. Shell scripts can automate system administration tasks
(3) The incorrect statement is that shell scripts typically perform better than compiled programs. In reality, shell scripts are generally slower in execution compared to compiled programs because they are interpreted at runtime, line by line, rather than being translated to machine code beforehand. Their advantage lies in development speed and flexibility, not execution performance.

  1. Run the script with sudo
  2. chmod +x scriptname.sh
  3. Change the shebang line
  4. Reboot the system
(2) The first command you should use is “chmod +x scriptname.sh” to add execute permissions to the script. A “Permission denied” error when trying to run a script with ./scriptname.sh typically indicates that the script lacks execute permissions, which must be granted before the script can be run as a program.

ComponentDescription
A. Shebang (#!)1. Specifies the path to the interpreter
B. chmod +x2. Makes a script executable
C. echo3. Displays text on the screen
D. ./4. Indicates the current directory path

A-1, B-2, C-3, D-4

  • Shebang (#!) specifies the path to the interpreter that should execute the script
  • chmod +x is the command used to make a script executable by adding execute permissions
  • echo is a command used to display text or variable values on the screen
  • ./ indicates the current directory path when running a script

SymbolMeaning
A. r1. The file can be executed
B. w2. The file can be viewed
C. x3. The file can be modified
D. -4. Permission is not granted

A-2, B-3, C-1, D-4

  • r (read) means the file can be viewed
  • w (write) means the file can be modified
  • x (execute) means the file can be executed as a program
    • (dash) means that particular permission is not granted

When a shell script with a shebang directive is executed, the following sequence occurs:

  1. The system checks if the file has execute permissions
  2. The system reads the shebang line to determine which interpreter to use
  3. The specified interpreter is invoked with the script file as an argument
  4. The interpreter processes each command in the script sequentially

This process allows the appropriate interpreter to execute the script according to the language or shell specified in the shebang.

To create a simple “Hello World” shell script in Linux:

  1. Create a new file: touch hello_world.sh
  2. Add the shebang line: echo '#!/bin/bash' > hello_world.sh
  3. Add the command to print “Hello World”: echo 'echo Hello World' >> hello_world.sh
  4. Make the script executable: chmod +x hello_world.sh
  5. Run the script: ./hello_world.sh

This will display “Hello World” on the terminal when executed.

The most common and recommended shebang for a Python 3 script is:

#!/usr/bin/env python3

This shebang uses the env command to locate the Python 3 interpreter in the user’s environment, making the script more portable across different systems where Python might be installed in different locations.

To check the current permissions of a file in Linux, use the ls -l command followed by the filename:

ls -l filename.sh

This will display a detailed listing that includes the file’s permissions, owner, group, size, and modification date. The permissions are shown in the leftmost column as a string like “-rwxr-xr-x”, where:

  • The first character indicates the file type
  • The next three characters (rwx) show permissions for the owner
  • The middle three characters show permissions for the group
  • The last three characters show permissions for others