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.

principle of least privleged access

The chmod operation allows the file owner to run a shell script. Note that “777” is too permissive for most environments.

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.

PowerShell vs Unix Shell

The difference between several common Windows PowerShell and Unix Bash commands

Step-by-step shell script execution

Follow these steps to create and run a shell script of your own from your Ubuntu home directory:

  1. Create a directory to store your shell script
  2. Create a file in your scripts folder with a .sh extension
  3. Add an execute permission to the file to avoid permission denied errors during execution
  4. Use the ./ (dot slash)  notation and run the shell script by name in the Terminal window
  5. 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
$ echo 'echo hello-world' >>
$ chmod -R 777 .
$ ./

And that’s how easy it is to create and run a script in Linux or Ubuntu.