Other Ways to Execute Scripts


The preceding example shows the most common way to run a shell script-that is, treating it as a program and executing the command file directly However, there are other ways to execute scripts that are sometimes useful.

Specifying Which Shell to Use

Many scripts start with a line that looks like this:

 #!/bin/sh

When you run a script like this, your shell reads the first line and interprets it to mean “run this script with /bin/sh.” This means that regardless of which shell you are using when you run the script, it will always be interpreted by sh. Since some scripts may not be compatible with all shells, this can help make your scripts more portable. For example, you could run this script even if you are using tcsh, and it will still work properly

Note, by the way, that this works with any program, not just /bin/sh. You could use the line #!/bin/bash to make your script run under bash. A Perl script might start with #!/usr/bin/perl, or a Python script with #! /usr/bin/python.

Explicitly Invoking the Shell

In all of the examples we have seen so far, your shell automatically starts a new subshell that reads and executes your script. You can explicitly start a subshell to run a script like this:

 $ sh scriptname

This will start an instance of sh that runs the commands in scriptname. When scriptname terminates, the subshell dies, and the original shell awakens and returns a system prompt. Because you are not executing the file scriptname directly, you do not need execute permission for it, although it must still be readable. Note that this will work even if sh is not your current shell.

Running Scripts in the Current Shell

When you run a script in a subshell, as all of the examples so far have done, the commands that are executed cannot change your current environment. For example, suppose you make some changes to your .profile, such as adding new environment variables or defining some aliases, and you want to test them. You could do

 $ -/.profile

if the file is executable, or

 $ ksh -/.profile

if it is not. But in either case, the changes to your environment are lost as soon as the script finishes and the subshell exits. Instead, you should use

 $ . -/.profile

The . (dot) command is a shell command that takes a filename as its argument and causes your current shell to read and execute the commands in it. Any changes to your current environment will remain even after the script is completed. When run with the . command, scripts do not need execute permission, only read permission.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net