Skip to main content
ubuntuask.com

Back to all posts

How to Execute A Shell Script on Linux?

Published on
9 min read
How to Execute A Shell Script on Linux? image

Best Programming Resources to Buy in October 2025

1 Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali

Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali

BUY & SAVE
$23.74 $39.99
Save 41%
Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali
2 Kali Linux OS for Hackers - Bootable Live Install USB Flash Thumb Drive - Cybersecurity Hacking Tools and Penetration Testing

Kali Linux OS for Hackers - Bootable Live Install USB Flash Thumb Drive - Cybersecurity Hacking Tools and Penetration Testing

  • DUAL CONNECTOR COMPATIBILITY: WORKS WITH ALL PCS, OLD AND NEW.

  • ETHICAL HACKING READY: OVER 600 TOOLS FOR ADVANCED SECURITY TESTING.

  • NO ACCOUNT NEEDED: FAST, PRIVATE, AND NO FORCED UPDATES FOR SEAMLESS USE.

BUY & SAVE
$19.99
Kali Linux OS for Hackers - Bootable Live Install USB Flash Thumb Drive - Cybersecurity Hacking Tools and Penetration Testing
3 Linux QuickStudy Laminated Reference Guide (QuickStudy Computer)

Linux QuickStudy Laminated Reference Guide (QuickStudy Computer)

  • SLEEK DESIGN ENHANCES ANY SPACE WITH MODERN APPEAL.
  • HIGH DURABILITY ENSURES LONG-LASTING PERFORMANCE.
  • VERSATILE FUNCTIONALITY MEETS DIVERSE STORAGE NEEDS.
BUY & SAVE
$6.95
Linux QuickStudy Laminated Reference Guide (QuickStudy Computer)
4 Kali Linux Everything OS Bootable USB - 600+ Expert Security Tools, Ethical Hacking, Penetration Testing, Cybersecurity, Hide IP

Kali Linux Everything OS Bootable USB - 600+ Expert Security Tools, Ethical Hacking, Penetration Testing, Cybersecurity, Hide IP

  • ALL-IN-ONE TOOLKIT: ACCESS EVERY TOOL IN THE KALI REPOSITORY EFFORTLESSLY.

  • ENTERPRISE READY: IDEAL FOR ORGANIZATIONS WITH STRICT COMPLIANCE REQUIREMENTS.

  • OFFLINE ACCESS: USE THE COMPLETE TOOLKIT WITHOUT NEEDING INTERNET CONNECTIVITY.

BUY & SAVE
$17.99
Kali Linux Everything OS Bootable USB - 600+ Expert Security Tools, Ethical Hacking, Penetration Testing, Cybersecurity, Hide IP
5 Practical Binary Analysis: Build Your Own Linux Tools for Binary Instrumentation, Analysis, and Disassembly

Practical Binary Analysis: Build Your Own Linux Tools for Binary Instrumentation, Analysis, and Disassembly

BUY & SAVE
$40.42 $59.99
Save 33%
Practical Binary Analysis: Build Your Own Linux Tools for Binary Instrumentation, Analysis, and Disassembly
6 Hacked: Kali Linux and Wireless Hacking Ultimate Guide With Security and Penetration Testing Tools, Practical Step by Step Computer Hacking Book

Hacked: Kali Linux and Wireless Hacking Ultimate Guide With Security and Penetration Testing Tools, Practical Step by Step Computer Hacking Book

BUY & SAVE
$6.80
Hacked: Kali Linux and Wireless Hacking Ultimate Guide With Security and Penetration Testing Tools, Practical Step by Step Computer Hacking Book
7 STREBITO Electronics Precision Screwdriver Sets 142-Piece with 120 Bits Magnetic Repair Tool Kit for iPhone, MacBook, Computer, Laptop, PC, Tablet, PS4, Xbox, Nintendo, Game Console

STREBITO Electronics Precision Screwdriver Sets 142-Piece with 120 Bits Magnetic Repair Tool Kit for iPhone, MacBook, Computer, Laptop, PC, Tablet, PS4, Xbox, Nintendo, Game Console

  • COMPLETE TOOLKIT: 120 BITS + 22 ACCESSORIES FOR ALL DIY PROJECTS!
  • ERGONOMIC DESIGN: COMFORT GRIP & SWIVEL TOP FOR EFFORTLESS USE.
  • ORGANIZED & PORTABLE: SECURE STORAGE IN SHOCK-PROOF BAG, EASY TO CARRY!
BUY & SAVE
$27.99
STREBITO Electronics Precision Screwdriver Sets 142-Piece with 120 Bits Magnetic Repair Tool Kit for iPhone, MacBook, Computer, Laptop, PC, Tablet, PS4, Xbox, Nintendo, Game Console
8 MTN TOOL Linux Distressed Dad Hat, Programmer Hat, Software Engineer, Systems Engineer Black

MTN TOOL Linux Distressed Dad Hat, Programmer Hat, Software Engineer, Systems Engineer Black

  • UNIQUE WORN LOOK: STAND OUT WITH STYLISH, VINTAGE APPEAL.
  • QUALITY EMBROIDERY: PROUDLY MADE IN THE USA FOR LASTING DURABILITY.
  • PERFECT FOR EVERYONE: TRENDY HAT FITS ALL, IDEAL FOR ANY OCCASION.
BUY & SAVE
$27.95
MTN TOOL Linux Distressed Dad Hat, Programmer Hat, Software Engineer, Systems Engineer Black
+
ONE MORE?

To execute a shell script on Linux, you need to follow these steps:

  1. Open a terminal: Launch the terminal application on your Linux system. You can usually find it in the applications menu or by using the keyboard shortcut Ctrl+Alt+T.
  2. Navigate to the script's location: Use the cd command to navigate to the directory where the shell script is located. For example, if the script is in your home directory, you can type cd ~ to go there.
  3. Check permissions: Ensure that the script has the execute permission. You can use the ls -l command to list the files in the directory and view their permissions. If your script doesn't have the execute permission (indicated by an 'x'), use the chmod +x scriptname.sh command to add it. Replace scriptname.sh with the actual name of your shell script.
  4. Execute the script: To run the shell script, simply type its name preceded by ./. For example, if your script is named myscript.sh, you would enter ./myscript.sh in the terminal.
  5. Press Enter: After typing the command, press the Enter key to execute the script.

That's it! The shell script will now be executed, and you will see the output or the actions performed by the script in the terminal. Remember to provide any required input when prompted by the script.

What is the exit status of a shell script on Linux?

The exit status of a shell script on Linux is a numerical value that indicates the outcome of the execution of the script.

By convention, an exit status of 0 typically indicates successful execution without any errors. Any non-zero value generally signifies some kind of error or failure. Different non-zero values can be used to convey specific types of errors or circumstances.

The exit status of a shell script can be manually set using the "exit" command within the script, or it can be implicitly determined by the return value of the last command executed in the script.

What is the purpose of comments in a shell script?

The purpose of comments in a shell script is to provide additional information and documentation about the code to make it more understandable and maintainable for both the script author and other developers who may need to read or modify the script later. Comments are non-executable lines that are ignored by the shell interpreter and are usually used to explain the purpose, logic, or functionality of the code. They can also be used to disable a particular block of code temporarily without deleting it. Comments improve the readability, clarity, and maintainability of the shell script.

What is the difference between environment variables and shell variables?

Environment variables and shell variables are both used to store values that can be accessed and used within the shell environment. However, there are some key differences between them.

  1. Scope: Environment variables are accessible by all processes in the current session, including child processes. They are inherited by all processes that are spawned by the current session. On the other hand, shell variables are only accessible within the current shell session or script and are not passed on to child processes.
  2. Persistence: Environment variables are typically stored in the system and persist across sessions, meaning they are available even after the session is closed and reopened. Shell variables, however, are temporary and exist only as long as the shell session or script is running.
  3. Setting and accessing: Environment variables are usually set and accessed using the shell's built-in export command like "export VARNAME=value". This allows them to be available to child processes. Shell variables, on the other hand, can be set and accessed directly without the need for the export command, using "VARNAME=value".
  4. Default values: Environment variables often have globally defined default values, set by the system or applications. Shell variables do not have any predefined default values and need to be explicitly set.

Overall, environment variables have a broader scope and are more useful for settings or values that need to be accessed by multiple processes, while shell variables are typically used for temporary and local use within the current shell session or script.

How to write a shell script on Linux?

To write a shell script on Linux, follow these steps:

  1. Open a text editor: Start by opening a text editor on your Linux system. Common text editors include "nano," "vi," or "gedit." Choose the one that you are comfortable with or prefer.
  2. Declare the script's interpreter: On the first line of the script, specify the interpreter to be used, such as bash, sh, or another shell. For example, to use the bash interpreter, start the script with #!/bin/bash.
  3. Write the code: Add the desired commands and actions to your script. Shell scripts can contain any valid Linux command or shell-built in functions. For example, you can include variable assignments, if statements, loops, and more.
  4. Add comments (optional): Include comments using the "#" symbol. Comments are helpful for documenting the script and explaining its functionality.
  5. Save the file: Save the file with a ".sh" extension to indicate that it is a shell script. For example, you can save it as "myscript.sh".
  6. Make the script executable (optional): If you want to run the script directly without specifying the interpreter, you need to make it executable. Open a terminal and use the chmod command to set the executable permissions. For example, run chmod +x myscript.sh.
  7. Run the script: To execute the script, open a terminal, navigate to the directory where the script is saved, and run ./myscript.sh if you made it executable. Otherwise, run bash myscript.sh or sh myscript.sh if you didn't make it executable.

By following these steps, you can create and execute a shell script on Linux.

How to pass arguments to a shell script on Linux?

There are a few different ways to pass arguments to a shell script on Linux. Here are a couple of common methods:

  1. Positional parameters: When you run a shell script, you can pass arguments directly after the script name. These arguments are called positional parameters and they are automatically assigned to special variables in the script, namely $1, $2, $3, and so on. For example, if your script is called "myscript.sh" and you want to pass two arguments, you can run: ./myscript.sh arg1 arg2 Inside the script, you can access these arguments using $1 and $2.
  2. Command-line options: Another way to pass arguments is to use command-line options. This is often done using the getopts command or by parsing the arguments manually. The getopts command is a built-in utility that allows you to define and handle options in your script. For example, you can define a script with an option -f that expects a filename as its argument: while getopts ":f:" opt; do case ${opt} in f ) file=$OPTARG;; \? ) echo "Invalid option: -$OPTARG"; exit 1;; : ) echo "Option -$OPTARG requires an argument"; exit 1;; esac done shift $((OPTIND -1)) In this case, you can run the script with the option and its argument: ./myscript.sh -f myfile.txt Inside the script, you can access the value of the argument with $file.

These are just two common methods for passing arguments to shell scripts on Linux. Depending on your specific requirements, there may be other approaches or techniques you can use.

What is a shell script and its purpose?

A shell script is a plain text file that contains a series of commands and instructions in a specific scripting language, such as Bash for Unix-like operating systems. Its purpose is to automate the execution of repetitive tasks or to combine multiple commands into a single script for easy execution.

Shell scripts are commonly used for system administration, software application deployment, and task scheduling. They allow users to write a sequence of commands that can be executed as a single unit, saving time and effort. Additionally, shell scripts can handle variables, loops, conditions, and logical operations, making them powerful for various automation scenarios.

How to debug a shell script on Linux?

Debugging a shell script on Linux can be done using the following methods:

  1. Enable debug mode: One way to debug a shell script is to enable debug mode by adding the following line at the beginning of the script: #!/bin/bash -x This will print each command and its arguments as they are executed.
  2. Add debug statements: Insert various echo statements in the script to print intermediate values, variable contents, or messages at strategic points. These statements can help in identifying the issues by tracking the flow of the script. #!/bin/bash echo "Script started." # some code... echo "Variable value: $var" # more code... echo "Script finished." By observing the output, you can locate where exactly the script is encountering problems.
  3. Use the set command: By using the set command with different options, you can enable additional debugging features such as tracing the command before it is executed (set -x), turning off or on tracing, exit on any error (set -e), etc. These options help in tracking the execution flow and identifying error-prone areas. #!/bin/bash set -x # Enable tracing # Rest of the script... set +x # Disable tracing
  4. Logging: Redirecting the output of the script to a log file or a specific debugging file can help capture any errors or debug information for further analysis. For example: #!/bin/bash exec 3>&1 4>&2 trap 'exec 2>&4 1>&3' 0 1 2 3 exec 1>log.out 2>&1 # Rest of the script... This will redirect all output (including error messages) to the specified log file.
  5. Use a shell debugger: Tools like bashdb and kshdb provide a debugging environment for shell scripts. They allow breakpoints, stepping through code, inspecting variables, and other features similar to traditional debuggers. For example, to use bashdb: $ bashdb script.sh This will start the debugger and allow you to interactively debug the script.

Remember to remove or disable any debugging code once the script is working as expected to avoid cluttering or affecting its performance.