How To Run A Shell Script

One may run or “execute”  shell scripts by typing it’s filename as a command and pressing <Enter> as they would with a regular command. However, the script file must must have executable permission set (see the previous post). Also, scripts may be given arguments and options similar to other programs.

Scripts stored in a directory on one’s path  may be run by simply typing the name of the file and pressing <Enter>. Otherwise one must provide a relative or full path to the location of the script file. Or if one’s current working directory contains the script file it can be run buy adding a “./” to the filename.

Examples…
Run a script named “hello” that is in a directory in your path…
$ hello <Enter>

Run a script named “hello” that is in your current working directory…
$ ./hello <Enter>

Run a script named hello that is in ~/MyScripts/ (a subdirectory of your “home” directory)…
$ ~/MyScripts/hello <Enter>

Posted in BSD, Bash, GNU/Linux, OS X Termial, Shell Script, UNIX | Tagged , , , , , | Leave a comment

Creating A Shell Script

Shell scripts are text files; subsequently one must use a text editor to produce them (not a word processor!) and then make the file executable so that it can be run. All Bash scripts contain a first line in one of two forms…

#!/bin/bash
or
#!/bin/sh

The #! tells the shell that the file contains executable commands and the path that follows tells the shell which program to run the commands with. The program used to run the script can be PERL, SED, AWK, another language or another shell.

The first option indicates that the shell is to use the Bash program itself (/bin/bash) to execute the script. The second option indicates the script is to be executed by (/bin/sh) which is a symbolic link to bash for backwards compatibility with older scripts. sh is the name of the old Bourne shell which Bash has replaced. Bash can run any Bourne script and many people still use /bin/sh to begin their scripts.

Example…
Write a Bash script that outputs the text “Hello world” to stdout…
Step 1. Create a new text document using a text editor and add the following lines…
#!/bin/bash
echo Hello world
then save the file as hello.
Step 2. Using chmod change the permissions on the file to make it executable…
$ chmod a+x hello <Enter>

Posted in BSD, Bash, GNU/Linux, Shell Script, UNIX | Tagged , , , , , | Leave a comment

Shell Scripts

Shells have a programming language. Many of the commands, utilities and tools I have discussed previously are a part of the shell script programming language. A shell program is simply a list of commands the shell can run. A shell script is a text file that contains a list of shell commands. These shell scripts are executable; subsequently one can run them by typing the shell script filename and pressing the <Enter> key.

The next few posts will discuss the basic concepts of shell scripts.

Posted in BSD, Bash, GNU/Linux, OS X Termial, UNIX | Tagged , , , , | Leave a comment