ATB Team

How to Run a .sh File on Linux

To run a .sh file on Linux you first need to ensure it has execute permissions by using chmod +x filename.sh. After that, you can run the script in different ways: with ./filename.sh if it’s in the current directory, or by calling the interpreter directly with bash filename.sh or sh filename.sh. Make sure the script includes a shebang line (e.g., #!/bin/bash) to specify the interpreter. If you encounter issues, check permissions or run with bash -x for debugging. For advanced users, adding the script to your PATH lets you run it from anywhere.

To run a .sh file (a shell script) on Linux, follow these steps:

1. Make the Script Executable

By default, shell scripts lack execute permissions. Use chmod to add them:

2. Run the Script

Method 1: Specify the Path

  • Note: The ./ tells Linux to look for the script in the current directory.
  • If you get a Permission denied error, revisit Step 1.

Method 2: Use the Shell Interpreter

or

  • Works even if the script lacks execute permissions.
  • Explicitly specifies the interpreter (Bash/sh).

Method 3: Full Path

  • Use if the script is in another directory (e.g., /home/user/scripts/).

3. Advanced Execution

Run in the Background

  • Adds & to detach the script from the terminal.

Log Output to a File

  • Redirects stdout and stderr to output.log.

Run as Root (if needed)

4. Verify the Shebang Line

Ensure the script starts with a shebang line (e.g., #!/bin/bash) to specify the interpreter:

  • If missing, the script may fail or use the wrong shell.

Troubleshooting

Permission Denied

“Command Not Found”

  • The script’s directory may not be in your PATH. Either:
  • Use the full path (e.g., ./script.sh).
  • Move the script to a directory in PATH (e.g., /usr/local/bin).

Windows Line Endings

If the script was created on Windows, convert line endings with:

Debugging

Add -x to trace execution:

Example Workflow

  1. Create a script:
  1. Make it executable:
  1. Run it:

Output:

Key Notes

  • Security: Never run untrusted scripts! Inspect the code first.
  • Arguments: Pass arguments to scripts like ./script.sh arg1 arg2.
  • Editing: Use nano, vim, or a GUI editor to modify scripts.

Summary Table

ActionCommand
Add execute permissionchmod +x script.sh
Run with path./script.sh
Run with Bash interpreterbash script.sh
Debugbash -x script.sh
Run as rootsudo ./script.sh
Fix Windows line endingsdos2unix script.sh

Leave a Comment

Table Of Content