Question: What are the basic fundamental things I should know to execute a shell script? Also, when I execute my shell script I get “Permission denied” error message. How do I fix it?
Answer: Let us review the 4 basic fundamental things you should know about executing a shell script.
1. Locate the shell executable and give it as she-bang #!
Identify the full path of where the shell is installed.
$ which sh /bin/sh (or) $ which ksh $ which bash
Once you’ve identified the location of the shell executable, give that as shebang ( #! ) in the first line of shell-script file.
$ vim helloworld.sh #!/bin/sh echo "Hello World!"
2. Assign Execute Permission to the Shell Script file
If you don’t have execute permission on the script, you’ll get “Permission denied” error message as shown below.
$ ./helloworld.sh bash: ./helloworld.sh: Permission denied
Assign execute permission to the script file using chmod command as shown below.
$ chmod u+x helloworld.sh
If you want to give execute permission to group and others, do it as shown below.
$ chmod 755 helloworld.sh
Note: You can also make this as an automatic process. i.e Whenever you open a shell script file, both the required things — adding the shebang, and giving execute permission can be done automatically using bash-support.vim plugin. Refer to our earlier article Make Vim as Your Bash-IDE Using bash-support Plugin for more details.
3. Execute the script by specifying absolute or relative path
You can execute a shell script either by using the absolute path or the relative path.
Execute the script by specifying the absolute path as shown below.
$ /home/ramesh/scripts/helloworld.sh Hello World!
Executing the script by specifying the relative path as shown below.
$ cd /home/ramesh/ $ ./scripts/helloworld.sh Hello World! (or) $ cd /home/ramesh/scripts $ ./helloworld.sh Hello World!
4. Executing the script just like a regular Linux command
You can also execute a script without specifying full path, absolute path or relative path. In order to do this, add the directory where all the shell script is located to your PATH environment variable as shown below.
For example, once I added /home/ramesh/scripts to the PATH environment variable, I can execute the script from any directory.
$ export PATH=$PATH:/home/ramesh/scripts $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/ramesh/scripts $ cd /go/to/anydirectory $ helloworld.sh Hello World!
Get the Linux Sysadmin Course Now!