Making a Script Executable

In the previous section, we showed you that you can run a shell script by typing sh followed by the name of the shell script file. You can also make a script executable, which means that you can run it simply by typing the script name at the shell prompt (omitting the name of the shell). Doing so is handy because it allows you to use the script as conveniently as you'd use any other command. As Code Listing 10.2 shows, you must set up a little before you can just execute the script.

Code Listing 10.2. After a little one-time preparation, you can run executable scripts by typing the script name at the shell prompt.

[ejr@hobbes scripting]$ head -2 myscript #!/bin/sh # This is my first shell script [ejr@hobbes scripting]$ chmod u+x myscript [ejr@hobbes scripting]$ pwd ; echo $PATH /home/ejr/scripting /usr/local/bin:/bin:/usr/bin:/usr/X11R6/  bin:/usr/local/games:/home/ejr/bin:/  home/ejr/scripting [ejr@hobbes scripting]$ myscript friendsjustfriends      standing      good [ejr@hobbes scripting]$ 


head -2 myscript

At the shell prompt, check to verify that your script does have the #!/bin/sh line at the top to specify the shell that runs it. Remember from Chapter 6 that head -2 will list the top two lines of the file specified.


chmod u+x myscript

Here, use the chmod command to give the user (that's you) execute permission. See the section in Chapter 5 called Changing Permissions with chmod for details on setting permissions.


pwd ; echo $PATH

Display the name of your current directory and the full path, and verify that the current directory is in the path. The current directory (the one in which you just granted yourself execute permission) must be contained in the path; otherwise, the script will not be as easily executable from the shell prompt.



At the shell prompt, type the name of the script. Assuming that your current directory is in the path, the script will run.


  • Every time you open up a new script, check to verify that the first line is #!/bin/sh so the file will run correctly. Also, check the permissions and your path to make sure you can run the script from the shell prompt. (You'll almost always find it more convenient to use executable scripts than to specify the shell or path each time you want to run a script.)

  • If the current directory isn't in the path (either explicitly or through a . notation, as in PATH=/usr/bin:.:), you'll have to take an additional step to execute the script. You could

    • Add the current directory to the path with something like PATH=$PATH:/home/yourid/tempdir. Read more about this option in Chapter 8.

    • Execute the script with ./myscript instead of just myscript.

    • Move the script to a directory in the path.

Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: