Monday, April 27, 2015

Different ways to run a shell script

Let the script be demoscript



Method1:

Make the script executable and run by calling its name (here "./" is used to signify that the script is present in current directory)

$ ./demoscript
  • The script must be executable.
        This can be done using chmod command as shown:
                        

  • A new shell is loaded into memory, which reads the commands from the file.
  • If any variables are set during the running of the script, then the values of those variables are immediately lost as soon as the shell  script stops running.
  •  It can be seen here that the variable GREETING set in the script is no longer set here in the current shell as here a new shell was used to run the script.



Method2:

Use any shell(here bourne shell is used) to execute the script.

$ sh demoscript


  • Same as method 1,but the file does not need to be made executable




Method3:

Use the current shell to run the script.

$ . demoscript


  • The commands in the script are executed by the "current" shell, if any variables are set, they still remain set after the script is finished
  • It can be seen that the variable GREETING set in the script is still set here in the current shell as here the current shell itself is used to run the script.




Method4:

Using source command.
$ source demoscript


  •  "source" command can be used to load any functions file into the current shell script or a command prompt.
  • It reads & execute commands from given filename & return





Method5:

Using exec command.
$ exec ./demoscript

  • The current shell terminates, spawning a new shell in its place to execute the script.
  • As soon as the script has terminated, the user is logged off.
  • Note that exec command takes the path of the file to be executed as argument.

No comments:

Post a Comment