How to Run a Shell Script in Linux: 5 Best Ways

Written by

Reviewed by

Last updated: July 24, 2024

Expert verified

SVG Image

TL;DR

Here are the best five ways to run shell scripts in Linux:

  1. Execute a shell script in Linux directly from the command line by navigating to the script’s directory using cd command, and run it with ./script_name.sh.
  2. Use the shebang #!/bin/bash as the first line in your shell script file, make it executable with chmod +x script_name.sh, and run it with ./script_name.sh.
  3. Run a shell script in Linux via the Bash command by changing to the script’s directory using cd command, and execute it with bash script_name.sh.
  4. Execute shell scripts in Linux using absolute paths by determining the script’s absolute path with pwd command, and run it using /absolute/path/to/script_name.sh.
  5. Utilize environment variables by setting them using export VARIABLE_NAME="value", and accessing them in your script for customized behavior.

Learn more about how to run a shell script in Linux and some troubleshooting tips to resolve its common errors.

Do you find yourself repeatedly typing the same commands in Linux? There’s a solution: shell scripting. Imagine automating tasks with a simple text file! In this post, I’ll show you how to create scripts that automate tasks like backups, updates, and more. You’ll learn various methods to run scripts, handle files, and even troubleshoot common errors. Let’s explore simplify your Linux workflow!

What is a Shell Script?

A shell script is a simple text file containing a sequence of commands that you would normally enter manually into the command line of a Unix-based operating system like Linux. It’s a powerful tool for automating and simplifying tasks.

Purpose:

  • Automation: Shell scripts automate repetitive tasks. Instead of typing the same commands every time, you can write them once in a script and run the script whenever needed. This saves time and reduces the chance of errors.
  • Task Scheduling: Using tools like cron, you can schedule shell scripts to run at specific times or intervals. This is useful for tasks like backups, updates, or regular maintenance.
  • Configuration Management: Shell scripts can set up and configure software systems quickly and consistently. They ensure that the configuration process is the same every time, which is crucial for maintaining stable and predictable systems.
  • Batch Processing: Shell scripts can process multiple files or data sets in a single run. For example, you can write a script to resize all images in a directory or convert multiple video files to a different format.
  • System Monitoring and Maintenance: Shell scripts can monitor system performance, check for errors, and perform routine maintenance tasks. For instance, they can check disk space and send an alert if it runs low.

Example:

Here’s a simple example of a shell script:

#!/bin/bash
# This is a comment
echo "Hello, World!" # This line prints "Hello, World!" to the terminal

How to Run a Shell Script in Linux [5 Simple Ways]

To run a shell script in Linux, simply make the script executable using the command chmod +x scriptname.sh, then execute it by typing ./scriptname.sh in the terminal. You can also use methods like adding a shebang (#!/bin/bash) at the script’s beginning, running it with the bash command, specifying absolute paths, or utilizing environment variables for flexibility. These options ensure efficient execution and automation of tasks on your Linux system.

Now, let’s explore each method’s detailed steps here:

1. Run Shell Scripts Directly

This method involves executing shell script in Linux directly from the command line. Here’s what you need to do:

  1. In the Terminal interface, create a script using the command
touch script_name.sh
  1. Then, open this script with nano script_name.sh and add the following script to the file:
#!/bin/bash

# This is a sample shell script

echo "Hello, World!"
echo "This script demonstrates how to run a script in Linux."

# Additional commands and functionality can be added here
  1. Save this script with Ctrl + O and then exit the Nano editor with Ctrl + X.
exit the nano editor run a shell script in linux
  1. Use the command below to run the script, where script_name.sh will be the name of your shell script file.
./script_name.sh
  1. Make the script executable with the command:
chmod +x script_name.sh
  1. Your shell script will execute, and you’ll get the following output in the Terminal:
your shell script will execute

2. Use Shebang (#!/bin/bash)

Shebang is a special sequence of characters (#!/bin/bash) placed at the beginning of a shell script file. It specifies the interpreter to use when executing the script. Follow the steps below to run a shell script in Linux:

  1. Open a text editor to create a new file for your shell script in Linux.
create a new file for your shell script in linux
  1. Add #!/bin/bash as the first line of the file, and add your script code below the shebang line.
#!/bin/bash
echo "This script demonstrates how to run a script in Linux with the Shebang notation."
  1. Save the file with the .sh extension (e.g., script_name.sh).
save the file with the sh extension
  1. Now, head to the Terminal and make the script executable using the command:
chmod +x script_name.sh
  1. Execute the script in the Terminal by running:
./script_name.sh
  1. The script will execute using the Bash interpreter specified in the shebang line and display the output in the Terminal.
bash interpreter specified in the shebang line

3. Run Shell Scripts via Bash Command

This method involves using the bash command to execute shell scripts explicitly. Follow the steps below to use this method:

  1. In the text editor, create a script file with the following content:
#!/bin/bash

echo "This script demonstrates how to run a script in Linux with the Bash command."
  1. Execute the script using the command below, where script_name.sh is the name of your shell script file:
 bash script_name.sh
  1. The script will run using the Bash interpreter, displaying the output in the Terminal.
script will run using the bash interpreter

4. Executing Shell Scripts Using Absolute Paths

In this method, you can execute shell scripts by specifying their absolute paths.

  1. Use cd to navigate to the directory where your script file is saved, and determine the absolute path of your shell script using the command:
pwd
  1. After that, make the script executable using the chmod command.
chmod +x scriptname.sh
  1. Then, execute the script by running the following command, replacing /absolute/path/to/ with the actual path of your script:
/absolute/path/to/script_name.sh
  1. Your script will execute using the specified absolute path and display the output in the Terminal.
script will execute using the specified absolute path

5. Utilizing Environment Variables

Environment variables provide a way to pass information to shell scripts during execution. Let’s create a script that uses an environment variable to customize its behavior:

  1. Open a text editor and write the following lines:
#!/bin/bash
echo "Welcome, $USERNAME!"
  1. Save the file as welcome.sh and close it.
save the file as welcome sh and close it
  1. Now, head to the Terminal and set an environment variable by running (replace “Name” with your desired username):
export USERNAME="Name"
  1. Make the script executable with the command:
chmod +x welcome.sh
  1. Then, execute the script by running:
./welcome.sh
  1. The script will execute and display a customized welcome message based on the value of the USERNAME environment variable.
welcome message based on the value of the username environment variable

4 Common Issues and Errors When Shell Scripting in Linux

Even with the best practices in place, shell scripting can sometimes encounter issues. In this section, I will discuss common problems and provide troubleshooting tips to help you overcome them.

  • ⚙️ Syntax Errors: Syntax errors in shell scripts can hinder proper execution. To troubleshoot them, you should double-check command syntax, ensure the correct placement of quotes, parentheses, and special characters, use linting tools for error detection and suggestions, and comment out sections to isolate the problematic line.
  • 🔒 Permission Denied Error: If you encounter a “Permission denied” error while executing a shell script, troubleshoot and resolve it by checking the file’s permissions using ls -l, granting execute permissions with chmod +x script_name.sh, and verifying correct ownership or group ownership.
  • ❗️ Command Not Found Error: When facing a “Command not found” error, ensure the required command is installed on your system, use which command_name to locate the command’s path, and update the script accordingly. Also, check accessibility in the current environment and consider modifying the PATH variable.
  • 🐞 Runtime Errors and Unexpected Output: If you encounter runtime errors or unexpected output during script execution, review error messages, implement error handling techniques like conditional statements and error codes, and debug the script using temporary echo statements or tools like set -x for tracing and identifying problematic code.

Wrapping Up

To wrap up, running shell scripts is pretty simple: create your script, make it executable, and run it. You can also use methods like shebang, running with the bash command, specifying absolute paths, and using environment variables. When you hit errors, check your script and use debugging tools.

For more learning, explore

Frequently Asked Questions

Can I run a shell script without the .sh extension?

Yes, it is indeed possible to run a shell script without using the .sh extension. However, it’s important to note that including the extension is considered a best practice. By using the .sh extension, you clearly indicate that the file is a shell script, which enhances readability and helps others understand its purpose at a glance.

Is it possible to pass command-line arguments to a shell script?

Absolutely! Shell scripts are capable of accepting command-line arguments. When executing the script, you can provide arguments that will be accessible within the script itself. These arguments can be accessed using special variables such as $1, $2, and so on. For instance, $1 represents the first argument, $2 represents the second argument, and so forth. This feature allows you to make your scripts more versatile and adaptable to different scenarios.

How can I check the exit status of a shell script?

To check the exit status of a shell script, you can rely on the special variable $?. After running a script, the value of $? holds the exit status. Typically, a value of 0 indicates successful execution, while non-zero values indicate errors or specific exit codes that you can define in your script. By examining the exit status, you can determine if the script was completed successfully or if there were any issues during execution.

Can I schedule the execution of shell scripts?

Certainly! You can schedule the execution of shell scripts using a powerful tool called cron. Cron allows you to define specific schedules for running your scripts automatically. You can set up tasks to run at predetermined intervals, such as daily, weekly, or monthly. By leveraging cron jobs, you can automate repetitive tasks and ensure that your scripts are executed without manual intervention.

What are some security considerations when running shell scripts?

When running shell scripts, it’s essential to be cautious about security. Here are a few considerations:
Only execute scripts from trusted sources.
Validate user inputs to prevent code injection vulnerabilities.
Limit script execution permissions to prevent unauthorized access.
Regularly update and patch your system to protect against known vulnerabilities.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

12 Best Ways to Use Grep Command in Linux 

Next Post

How to Use chmod 755 in Linux [3 Best Ways]

Read next