Running scripts

If you were really paying attention, you will have noticed we executed a script that was not executable, using the bash command. Why would we need the shebang, if we specify how to run it anyway? In this case, we would not need the shebang. However, we would need to know exactly which kind of script it is and find the correct binary on the system to run it, which can be kind of a hassle, especially once you have many scripts. Thankfully, there is a better way for us to run these scripts: using the executable permission. Let's see how we can run our hello-world.sh script by setting the executable permission:

reader@ubuntu:~/scripts/chapter_07$ ls -l
total 4
-rw-rw-r-- 1 reader reader 33 Aug 26 12:08 hello-world.sh
reader@ubuntu:~/scripts/chapter_07$ ./hello-world.sh
-bash: ./hello-world.sh: Permission denied
reader@ubuntu:~/scripts/chapter_07$ chmod +x hello-world.sh
reader@ubuntu:~/scripts/chapter_07$ ./hello-world.sh
Hello World!
reader@ubuntu:~/scripts/chapter_07$ /home/reader/scripts/chapter_07/hello-world.sh
Hello World!

reader@ubuntu:~/scripts/chapter_07$ ls -l
total 4
-rwxrwxr-x 1 reader reader 33 Aug 26 12:08 hello-world.sh
reader@ubuntu:~/scripts/chapter_07$

We can execute a script (or any file, really, if it makes sense for the file to be executed) by either running it fully qualified or using ./ in the same directory, as long as it has the executable permission set. We need the prefix ./ because of security: normally when we execute a command the PATH variable is explored for that name. Now imagine someone putting a malicious binary called ls in your home directory. If ./ rule wasn't in place, running the ls command would result in the binary being run, instead of /bin/ls (which is on your PATH).

Because we are running a script by just using ./hello-world.sh, we now need the shebang again. Otherwise, Linux would default to using /bin/sh, which is not what we want in a Bash scripting book, right?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.164.141