Shell Processes   «Prev  Next»
Lesson 7 Specifying the shell in a script />
Objective Using #! on the first line of a script.

Specifying Shell in Script

  1. Is there a difference between a notation and a command?
  2. Is #! Also a command?
  3. Should we define or gloss the word notation in the text?
Eliminate the word notation so there will not be confusion here.
To indicate the shell for which a script is written, use the following on the first line of your script:
#! /bin/sh

The #! must be the first two characters in your file, followed by the program name
Am I right in thinking that bin/sh is more than just the shell name?
It is the path, right? (because of the bin?) please explain.
ok
of the shell to be used.


How #! works

When you run the script, the shell looks for #! on the first line. After finding it, your script runs using the indicated shell
Does that mean it first starts the shell? Or does it not have to start a shell in order torun a script with it?

I purposely did not explain this in detail because it gets involved. It will not matter to someone writing a script – they just need to know that the shell is indicated on the #! Line. Using #! on the first line of your script ensures that your script will run using the correct shell. If this line is not inserted at the top of your script, then your shell might assume you are using Bourne, Korn, or C shell without any consistency. It is better to know which shell your script will be run under by including the #! on the first line.

Technique number one only

Of the three techniques listed in the previous lesson, only technique number one (typing the script name in on the command line) reads the first line of the file to check for the #!. The other two techniques see the #! line as a commentany particular reason that this happens, or is that totally irrelevant? Just theway the techniques work.

Three ways to run a Shell Script

Technique number Command permissions Subprocess created?
1 Myscript r-x Yes:runs as a child process of the current shell
2 /bin/sh myscript r-- Yes:runs as a child process of the current shell
3 . myscript r-- No:runs inside the current shell

How do I run .sh files?

Give execute permission to your script:
chmod +x /path/to/yourscript.sh

To run your script:
/path/to/yourscript.sh

Since . refers to the current directory: if yourscript.sh is in the current directory, you can simplify this to:
./yourscript.sh				             

The next lesson looks at the shell PATH variable.


SEMrush Software