How to Run a .sh File in Linux
In Linux, shell scripts (.sh files) are widely used to automate tasks, configure systems, or deploy applications. Knowing how to run them is essential for administrators, developers, and anyone working with Linux servers. In this guide, we’ll explain different methods step by step.
1. Make the File Executable
When you download or create a .sh file, it may not have execution permissions by default. To add them, use:
Now the file can be executed as a program.
2. Run with Relative or Absolute Path
If the file is in the current directory:
If it’s located elsewhere:
3. Run with bash or sh
Even without execution rights, you can run the script directly with the shell:
or
This method is useful for testing scripts quickly.
4. Run as Superuser (if required)
Some scripts require elevated privileges to modify the system. In that case:
or
5. Run in the Background
If you want the script to run without blocking your terminal session:
The & symbol sends the process to the background.
6. Scheduling Script Execution
To automate repeated execution, you can use cron:
Example:
This runs the script every day at 2 AM.
Best Practices
- Always check the contents of a .sh file before running it, especially if it comes from an external source.
- Use comments inside scripts (#) to make them clear and maintainable.
- Keep scripts in dedicated directories like /usr/local/bin or ~/scripts.
Conclusion
Running .sh files in Linux is straightforward: give them execution permission, then run them via ./script.sh or with bash. For server automation and reliability, place them on a VPS or dedicated server like those offered by AlexHost, and use cron jobs for regular tasks.