We hardly care about how a shell script executes, the only thing which we care about is that scripts should execute without any bugs. Here, we are going to discuss about some ways of running a script.
Before seeing the ways of running a shell script, let me clear a question. What is a Shell Script?
We all execute commands on shell. A shell is a program which provides us the environment to execute commands. This also means that we need to have shell running before we start running commands. Now, a shell script is nothing but collection of commands. We club some commands in a file and then ask the interpreter to run the file. This file, where we club our commands is known as interpreter file. Please note that it is not the interpreter file which executes, but the contents of the interpreter file is executed by interpreter, and interpreter is nothing but the shell. Not going in much details into shell and interpreters, we assume that now we know that a shell or interpreter is very necessary for execution of Shell Scripts.
Let's see the ways of running a script
1) /bin/sh testscript.sh
This is the first way in which we specify that we want to run the script using bash shell. Now, the main shell will fork a new shell and that subshell/interpreter will execute the shell script.
Note: We will not be able to access any variables from parent shell unless they are exported.
2) ./testscript.sh or {full-path}/testscript.sh
This is the second way in which we don't specify the shell name. Infact, we write a special line at the top of the interpreter file
#! /bin/sh
# in shell script means that the line is a comment, but # in the first line defines the interpreter to be used for running the script. This line is known as shebang line.
Note: If we don't specify shebang line in this format of running the script then by default, the executing shell will be of same type as the user's login shell. For ex: If the user's default login shell is ksh then ksh shell will be used for running the script.
It is necessary to give relative or full path of script, if we type only script name on the command line, the shell will treat it as a command and start searching in the PATH for the executable file of this command. We can set PATH variable to contain the script path if want to run the script using the script name only.
3) . ./testscript.sh
If we leave first dot, it is same as the second one, then what change does this first dot brings?
Here first dot means script will be run using the same/current shell, i.e. don't fork a new subshell for running the script. The script will be able to use all the variables of the current shell because it is running on the current shell.
For more info visit
No comments:
Post a Comment