How to Run a .sh File in Linux: Complete Guide for Beginners and Sysadmins
Shell scripts are the backbone of Linux automation. Whether you're deploying a web application, scheduling backups, or configuring a freshly provisioned server, .sh files let you bundle complex command sequences into a single, repeatable executable. This guide walks you through every method for running shell scripts in Linux — from basic execution to background processes and cron scheduling — with best practices that hold up in production environments.
What Is a .sh File in Linux?
A .sh file is a plain-text script written in shell language (typically Bash or POSIX sh) that the Linux shell interprets and executes line by line. Shell scripts are used to:
- Automate repetitive system administration tasks
- Deploy and configure applications
- Manage users, permissions, and file systems
- Schedule maintenance jobs like backups and log rotation
- Bootstrap new servers after provisioning
If you're managing a VPS Hosting environment or a Dedicated Server, shell scripting is an indispensable skill that will save you hours of manual work every week.
Prerequisites
Before running any .sh file, make sure you have:
- Access to a Linux terminal (local or via SSH)
- A user account with appropriate permissions
- The script file already on the system (created locally or transferred via SCP/SFTP)
Method 1: Make the File Executable with chmod
By default, newly created or downloaded .sh files do not have execution permissions. Before running the script as a program, you must explicitly grant execute rights using the chmod command.
chmod +x script.shTo verify the permissions were applied correctly:
ls -l script.shYou should see output similar to:
-rwxr-xr-x 1 user user 1024 Jun 10 14:32 script.shThe x flags confirm the file is now executable by the owner, group, and others.
> Security tip: If you want to restrict execution to only the file owner, use chmod 700 script.sh instead of chmod +x.
Method 2: Run the Script Using a Relative or Absolute Path
Once the file is executable, you can run it directly from the terminal.
Using a Relative Path (Current Directory)
If the script is in your current working directory, prefix it with ./:
./script.shThe ./ tells the shell to look in the current directory rather than searching the system $PATH.
Using an Absolute Path
If the script is stored in another location, provide its full path:
/home/user/scripts/script.shor
/usr/local/bin/script.shUsing absolute paths is especially important when running scripts from cron jobs or other automated contexts where the working directory may differ.
Method 3: Run the Script with bash or sh (No Execute Permission Required)
You can invoke a shell script by explicitly calling the interpreter, even if the file lacks execute permissions. This is particularly useful for quickly testing a script before making it permanently executable.
bash script.shor, for POSIX-compliant scripts:
sh script.shDifference Between bash and sh
| Command | Interpreter | Supports Bash-Specific Features |
|---|---|---|
bash script.sh | GNU Bash | Yes |
sh script.sh | POSIX sh (often dash on Ubuntu) | No |
If your script uses Bash-specific syntax like arrays, [[ ]] conditionals, or process substitution, always use bash rather than sh.
Method 4: Run the Script as Superuser (sudo)
Some scripts require root-level privileges to modify system files, manage services, install packages, or change network configurations. Use sudo to elevate permissions:
sudo ./script.shor pass the script directly to bash with elevated rights:
sudo bash script.shImportant Security Considerations
- Never run a script as root without reading it first. A malicious or poorly written script with sudo access can cause irreversible system damage.
- Prefer running scripts with the minimum required privileges.
- If a script only needs to write to a specific directory, consider adjusting directory permissions rather than running the entire script as root.
Method 5: Run the Script in the Background
By default, running a script in the terminal blocks your session until the script completes. For long-running tasks — such as large file transfers, database migrations, or server builds — you'll want to send the process to the background.
Using the & Operator
./script.sh &The & symbol forks the process into the background and immediately returns control to your terminal. The shell prints the background job's PID (Process ID), which you can use to monitor or terminate it later.
Keep the Script Running After Logout with nohup
If you disconnect from SSH, background jobs launched with & will typically terminate. Use nohup to prevent this:
nohup ./script.sh &Output is redirected to nohup.out by default. To specify a custom log file:
nohup ./script.sh > /var/log/myscript.log 2>&1 &Monitor Background Jobs
jobs # List background jobs in the current session
ps aux | grep script.sh # Find the process by name
kill PID # Terminate a specific background processMethod 6: Schedule Script Execution with Cron
For recurring tasks — nightly backups, weekly cleanups, hourly health checks — Linux's built-in cron scheduler is the standard solution.
Open the Crontab Editor
crontab -eCron Syntax
* * * * * /path/to/script.sh
│ │ │ │ │
│ │ │ │ └── Day of week (0–7, Sunday = 0 or 7)
│ │ │ └──── Month (1–12)
│ │ └────── Day of month (1–31)
│ └──────── Hour (0–23)
└────────── Minute (0–59)Practical Cron Examples
| Schedule | Cron Expression | Example Use Case |
|---|---|---|
| Every day at 2:00 AM | 0 2 * * * | Nightly database backup |
| Every Monday at 6:00 AM | 0 6 * * 1 | Weekly log rotation |
| Every hour | 0 * * * * | Uptime monitoring check |
| Every 15 minutes | */15 * * * * | Cache refresh |
| On system reboot | @reboot | Start a service or script at boot |
Example: Automated Daily Backup
0 2 * * * /home/user/scripts/backup.sh >> /var/log/backup.log 2>&1This runs backup.sh every day at 2:00 AM and appends both standard output and errors to a log file for auditing.
> Pro tip: Always use absolute paths in cron entries. Cron runs with a minimal environment and may not have access to the same $PATH as your interactive shell.
Method 7: Source a Script (Run in Current Shell Context)
There is one more execution method worth knowing: sourcing a script. Unlike the methods above, sourcing runs the script within the current shell session rather than spawning a subshell. This means any variables or functions defined in the script persist in your current environment.
source script.shor equivalently:
. script.shThis is commonly used for loading environment variables, activating virtual environments, or applying configuration changes to the current session.
Troubleshooting Common Errors
| Error Message | Likely Cause | Solution |
|---|---|---|
Permission denied | File lacks execute permission | Run chmod +x script.sh |
No such file or directory | Wrong path or missing file | Verify path with ls and pwd |
bad interpreter: No such file or directory | Wrong shebang line (e.g., Windows line endings) | Run dos2unix script.sh to fix line endings |
command not found | Script not in $PATH and no ./ prefix | Use ./script.sh or full absolute path |
syntax error near unexpected token | Script written for bash but run with sh | Use bash script.sh explicitly |
Best Practices for Writing and Running Shell Scripts
Following these practices will make your scripts safer, more maintainable, and easier to debug — especially in server environments.
1. Always Start with a Shebang Line
The first line of every script should declare the interpreter:
#!/bin/bashor for maximum portability:
#!/usr/bin/env bash2. Enable Strict Mode
Add this near the top of every production script:
set -euo pipefail-e— Exit immediately if any command fails-u— Treat unset variables as errors-o pipefail— Catch failures in piped commands
3. Read the Script Before Running It
Never execute a .sh file from an external or untrusted source without reviewing its contents first:
cat script.shor open it in a text editor. This is especially critical when running with sudo.
4. Use Comments Liberally
#!/bin/bash
# backup.sh — Daily backup script for /var/www
# Author: sysadmin@example.com
# Last updated: 2024-06-10
# Define source and destination directories
SOURCE="/var/www"
DEST="/mnt/backup"5. Organize Scripts in Dedicated Directories
| Directory | Recommended Use |
|---|---|
/usr/local/bin/ | System-wide scripts accessible to all users |
~/scripts/ or ~/bin/ | Personal user scripts |
/opt/scripts/ | Application-specific automation scripts |
/etc/cron.daily/ | Scripts to run daily via cron |
6. Log Script Output
Always redirect output to a log file for scripts running unattended:
./script.sh >> /var/log/script.log 2>&17. Test Scripts in a Safe Environment First
Before deploying a script to a production server, test it on a staging environment or a disposable VPS instance where mistakes won't cause downtime.
Running Shell Scripts on a Linux Server: Practical Considerations
When running scripts on a remote Linux server — whether it's a shared environment or a dedicated machine — a few additional factors come into play:
- SSH access: Most server-side scripting happens over SSH. Tools like
screenortmuxlet you maintain persistent sessions so long-running scripts survive disconnections. - User permissions: On shared hosting environments, your ability to execute scripts may be limited. A VPS with cPanel gives you full root access and complete control over script execution.
- Automated deployments: Combine shell scripts with cron jobs to automate deployments, certificate renewals (especially useful alongside SSL Certificates), and routine maintenance tasks.
- Environment variables: Scripts running via cron or SSH may not inherit your interactive shell's environment. Define all necessary variables explicitly within the script or source a profile file.
Quick Reference: All Methods at a Glance
| Method | Command | Use Case |
|---|---|---|
| Execute with permission | chmod +x script.sh && ./script.sh | Standard execution |
| Run with bash | bash script.sh | No execute permission needed |
| Run with sh | sh script.sh | POSIX-compatible scripts |
| Run as root | sudo ./script.sh | Scripts requiring elevated privileges |
| Run in background | ./script.sh & | Non-blocking execution |
| Run persistently | nohup ./script.sh & | Survive SSH logout |
| Schedule with cron | crontab -e | Recurring automated tasks |
| Source the script | source script.sh | Apply changes to current shell |
Conclusion
Running .sh files in Linux is a fundamental skill that unlocks the full power of system automation. The core workflow is simple: grant execute permission with chmod +x, then run the script with ./script.sh or bash script.sh. For production environments, combine absolute paths, strict mode, logging, and cron scheduling to build robust, reliable automation pipelines.
If you're managing scripts on a server, the quality of your hosting infrastructure matters. AlexHost's VPS Hosting and Dedicated Servers give you full root access, stable uptime, and the performance you need to run automation workloads confidently — whether you're scheduling nightly backups, deploying applications, or managing complex multi-script workflows.
