How To Run Sh File On Linux : Shell Script Permissions Guide

Executing a shell script on Linux begins with making sure the file is executable using the `chmod` command. If you’re wondering how to run sh file on linux, the process is straightforward once you understand the permissions and path requirements. Shell scripts (.sh files) are powerful tools for automating tasks, and running them correctly is a fundamental skill for any Linux user.

This guide walks you through every step, from creating a simple script to troubleshooting common errors. You’ll learn the exact commands and best practices to execute .sh files efficiently.

Understanding Shell Scripts And Permissions

Before you run a .sh file, you need to know what it is. A shell script is a text file containing a sequence of commands for the Linux shell (like Bash) to execute. The .sh extension is just a naming convention; Linux doesn’t require it, but it helps identify the file type.

Linux uses a permission system to control who can read, write, or execute files. For a script to run, the file must have execute permission. This is where the `chmod` command comes in.

Checking Current File Permissions

To see the current permissions of your script, use the `ls -l` command. Open your terminal and type:

ls -l yourscript.sh

You’ll see output like -rw-r--r--. The first character indicates the file type (- for regular file). The next nine characters represent permissions for the owner, group, and others. If you don’t see an ‘x’ (execute) in any of these groups, the script isn’t executable yet.

Making The Script Executable With Chmod

The `chmod` command changes file permissions. To add execute permission for the owner, use:

chmod u+x yourscript.sh

If you want everyone to be able to execute it, use:

chmod +x yourscript.sh

Now when you run ls -l, you should see -rwxr-xr-x or similar, indicating execute permission is set.

How To Run Sh File On Linux

Now that your script has execute permission, you can run it. There are several methods, each with its own use case.

Method 1: Using The Full Path

The most common way is to type the full or relative path to the script. If you’re in the same directory, use:

./yourscript.sh

The ./ tells the shell to look in the current directory. Without it, Linux searches directories listed in the PATH environment variable, which typically doesn’t include the current directory for security reasons.

Method 2: Using The Bash Command

You can also run a script by passing it as an argument to the Bash interpreter:

bash yourscript.sh

This method doesn’t require execute permission on the file. It’s useful for testing scripts or running scripts you don’t want to make executable permanently.

Method 3: Using Sh Command

Similarly, you can use the `sh` command, which often points to the default system shell:

sh yourscript.sh

Be cautious: `sh` might not be Bash on all systems (e.g., on Ubuntu, it’s Dash). This can cause syntax errors if your script uses Bash-specific features.

Method 4: Adding The Script To PATH

If you want to run the script from anywhere without typing the path, add its directory to your PATH environment variable. For example, to add the current user’s bin directory:

  1. Create a directory: mkdir -p ~/bin
  2. Move your script there: mv yourscript.sh ~/bin/
  3. Add to PATH in your .bashrc file: export PATH="$HOME/bin:$PATH"
  4. Reload the file: source ~/.bashrc

Now you can run yourscript.sh from any directory.

Creating A Simple Shell Script To Test

Let’s create a basic script to practice. Open a text editor and type:

#!/bin/bash
echo "Hello, World!"
echo "Current date: $(date)"

Save it as test.sh. The first line (#!/bin/bash) is called a shebang. It tells the system which interpreter to use. Without it, the script might run with a different shell, causing errors.

Now make it executable and run it using one of the methods above.

Common Shebang Lines

  • #!/bin/bash – For Bash scripts
  • #!/bin/sh – For POSIX-compliant scripts
  • #!/usr/bin/python3 – For Python scripts
  • #!/usr/bin/env bash – More portable, finds Bash in the user’s PATH

Troubleshooting Common Errors

Even experienced users run into issues. Here are the most common problems and solutions.

Permission Denied Error

If you see bash: ./script.sh: Permission denied, the file lacks execute permission. Run chmod +x script.sh to fix it.

Command Not Found Error

If you get bash: script.sh: command not found, you forgot the ./ prefix. Type ./script.sh instead of just script.sh.

Bad Interpreter Error

Errors like bash: ./script.sh: /bin/bash^M: bad interpreter usually mean the file has Windows-style line endings. Convert it with:

dos2unix script.sh

Or use sed -i 's/\r$//' script.sh.

Syntax Errors

If you see unexpected syntax errors, check for missing spaces, quotes, or Bash-specific features when using `sh` instead of `bash`. Always use bash script.sh if you’re unsure.

Running Scripts With Arguments

Many scripts accept arguments. Inside the script, you can access them using $1, $2, etc. For example, create a script called greet.sh:

#!/bin/bash
echo "Hello, $1!"

Make it executable and run:

./greet.sh Alice

Output: Hello, Alice!

You can pass multiple arguments separated by spaces. Use $@ to access all arguments at once.

Using Quoted Arguments

If an argument contains spaces, enclose it in quotes:

./greet.sh "John Doe"

Otherwise, “John” and “Doe” become two separate arguments.

Running Scripts In The Background

Sometimes you want a script to run without blocking the terminal. Append an ampersand (&) to run it in the background:

./longscript.sh &

You’ll get a job number and process ID. The script runs, and you can continue using the terminal. To bring it back to the foreground, use fg (with the job number if multiple).

Using Nohup For Persistent Background Jobs

If you close the terminal, background jobs usually stop. Use nohup to prevent this:

nohup ./script.sh &

Output is saved to nohup.out by default. You can redirect it:

nohup ./script.sh > output.log 2>&1 &

Running Scripts With Sudo

Some scripts need root privileges. Use sudo:

sudo ./script.sh

Be careful: running scripts as root can be dangerous. Only do this if you trust the script and understand what it does.

Using Source To Run Scripts In The Current Shell

Normally, scripts run in a subshell. Changes to environment variables or the current directory don’t affect the parent shell. To run a script in the current shell, use the source command or its shorthand .:

source script.sh

Or:

. script.sh

This is useful for scripts that set environment variables or change directories.

Best Practices For Running Shell Scripts

Follow these tips to avoid common pitfalls and write robust scripts.

  • Always include a shebang line.
  • Make scripts executable only when needed.
  • Test scripts with bash -n script.sh to check syntax without running.
  • Use set -e at the start to exit on errors.
  • Quote variables to handle spaces: "$1" instead of $1.
  • Keep scripts in a dedicated directory like ~/scripts.
  • Use version control (Git) for important scripts.

Advanced: Running Scripts From Other Directories

You can run a script from anywhere by providing the full path. For example:

/home/user/scripts/deploy.sh

Or use relative paths:

../scripts/deploy.sh

If you frequently run scripts from a specific directory, consider adding it to PATH as described earlier.

Using Symbolic Links

Another approach is to create a symbolic link in a directory that’s already in PATH:

ln -s /path/to/script.sh ~/bin/myscript

Now you can run myscript from anywhere.

Running Scripts At Boot Or On Schedule

To run a script automatically at system startup, add it to /etc/rc.local (on older systems) or create a systemd service. For scheduled tasks, use cron:

  1. Edit your crontab: crontab -e
  2. Add a line like: 0 5 * * * /path/to/script.sh (runs daily at 5 AM)
  3. Save and exit.

Security Considerations

Running scripts from untrusted sources can compromise your system. Always review the code before executing. Use cat or less to view the script:

cat script.sh

Check for dangerous commands like rm -rf /, wget with pipe to bash, or suspicious network connections.

When downloading scripts from the internet, consider using curl -O and then inspect the file before running.

Frequently Asked Questions

What If My .Sh File Doesn’t Have A Shebang Line?

Without a shebang, the system uses the default shell (usually Bash). It might work, but it’s unreliable. Always add #!/bin/bash for clarity.

Can I Run A .Sh File Without Making It Executable?

Yes, use bash filename.sh or sh filename.sh. This bypasses the need for execute permission.

Why Do I Get “./” Before The Script Name?

The ./ tells the shell to look in the current directory. Without it, the shell searches PATH, which usually doesn’t include the current directory.

How Do I Run A Script With Spaces In Its Name?

Enclose the name in quotes or escape the spaces: "./my script.sh" or ./my\ script.sh.

What’s The Difference Between Bash And Sh?

Bash is a superset of sh with additional features. On many systems, sh is a symlink to Dash, which is faster but less feature-rich. Use bash for scripts that need Bash-specific syntax.

Running .sh files on Linux is a core skill that opens up automation possibilities. Start with simple scripts, practice the different methods, and gradually move to more complex tasks. Remember to always check permissions and test in a safe environment first.