Run shell scripts in Linux
It’s pretty easy to run a batch file on windows.
Just just create a file, change the extension to .bat, and either call the script in PowerShell or double click to execute it. Windows users are spoiled.
If you want to create a script and run it in Ubuntu, a few extra steps are involved.
Shell scripts vs batch files
First, Ubuntu runs shell scripts, not batch files, so your file must have a .sh extension.
Secondly, Ubuntu forbids users from being allowed to run any scripts without execute permissions being applied to the file.
Ubuntu respects the principle of least privilege, so it always assigns files the minimal permissions it think your need to do your work. For the most part, that means read and write access.
So to run a script, a quick chmod operation is required, lets your attempt to run a shell script in Ubuntu will encounter a permission denied error.
And finally, when you run an Linux shell script in an Ubuntu terminal window, you need to prepend a dot slash to the file’s name. If you don’t, Ubuntu will look on the operating system’s PATH for your program.
The ./ notation instructs Linux to search for the script you are trying to run in the current directory in which you are working.
Step-by-step shell script execution
Follow these steps to create and run a shell script of your own from your Ubuntu home directory:
- Create a directory to store your shell script
- Create a file in your scripts folder with a .sh extension
- Add an execute permission to the file to avoid permission denied errors during execution
- Use the ./ (dot slash) notation and run the shell script by name in the Terminal window
- Press CTRL+C to stop the running Linux script if it does not terminate gracefully
The steps described above are manifest in the six commands provided below:
$ mkdir scripts $ cd scripts $ touch script.sh $ echo 'echo hello-world' >> script.sh $ chmod -R 777 . $ ./script.sh hello-world
And that’s how easy it is to create and run a script in Linux or Ubuntu.