How to create and run a shell script in Linux and Ubuntu
It’s pretty easy to run a batch file on Windows. 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. Linux users can create and run shell scripts too, with a little more effort.
Run shell scripts in Linux
If you want to create a script and run it in Ubuntu, a few extra steps are involved.
First, Ubuntu runs shell scripts, not batch files, so your file must have a .sh extension.
Secondly, Ubuntu forbids users to run any scripts on a file unless it has execute permissions.
Ubuntu respects the principle of least privilege, so it always assigns files the minimal permissions it thinks you need to do your work. For the most part, that means read and write access.
So to run a script, you’ll need a quick chmod operation. Otherwise, your attempt to run a shell script in Ubuntu encounters a permission denied error.
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 want to run in the directory where you are currently 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 following six commands:
$ 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.