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:
chmod +x your_script.sh
2. Run the Script
Method 1: Specify the Path
./your_script.sh
- 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
bash your_script.sh
or
sh your_script.sh
- Works even if the script lacks execute permissions.
- Explicitly specifies the interpreter (Bash/sh).
Method 3: Full Path
/path/to/your_script.sh
- Use if the script is in another directory (e.g.,
/home/user/scripts/
).
3. Advanced Execution
Run in the Background
./your_script.sh &
- Adds
&
to detach the script from the terminal.
Log Output to a File
./your_script.sh > output.log 2>&1
- Redirects stdout and stderr to
output.log
.
Run as Root (if needed)
sudo ./your_script.sh
4. Verify the Shebang Line
Ensure the script starts with a shebang line (e.g., #!/bin/bash
) to specify the interpreter:
#!/bin/bash
echo "Hello, World!"
- If missing, the script may fail or use the wrong shell.
Troubleshooting
Permission Denied
chmod +x your_script.sh # Fix permissions
“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:
sudo apt install dos2unix # Install tool (Debian/Ubuntu)
dos2unix your_script.sh # Convert CRLF to LF
Debugging
Add -x
to trace execution:
bash -x your_script.sh
Example Workflow
- Create a script:
echo '#!/bin/bash
echo "Today is $(date)"' > my_script.sh
- Make it executable:
chmod +x my_script.sh
- Run it:
./my_script.sh
Output:
Today is Wed Sep 20 10:00:00 UTC 2023
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
Action | Command |
---|---|
Add execute permission | chmod +x script.sh |
Run with path | ./script.sh |
Run with Bash interpreter | bash script.sh |
Debug | bash -x script.sh |
Run as root | sudo ./script.sh |
Fix Windows line endings | dos2unix script.sh |