npressfetimg-6382.png

How to create and run a shell script in Linux and Ubuntu – TheServerSide.com

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.

The chmod operation is required to allow the file owner to run a shell script. It should be noted that 777 will be too permissive for most environments.

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:

  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 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.

The difference between Windows PowerShell and Unix Bash commands

Source: https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/run-Unix-shell-script-Linux-Ubuntu-command-chmod-777-permission-steps

Related Posts