jbsnake :
The basics of writing BASH shell scripts
written by jbsnake, reposted by crouse.
------------------------------------------------------
This tutorial will (hopefully) teach you the basics of writing BASH shell scripts. The original shell written by Steven Bourne was called sh or Bourne Shell. BASH is compatible with the original Bourne shell. BASH stands for Bourne Again SHell.
There are four different parts to a standard shell script. They are:
commands,
comments,
functions, and
variables.
Comments: The reason I listed comments as a major part of a standard shell script is because it is highly important (not to mention nice) to include as much help within a script as possible for the user. Not just the user can benefit from comments, it also helps the writer (you) remember what you were doing in a particular part of the script. That way changes are easier to make.
Commands: are the guts of the shell scripts. Without the commands (ex:
echo) the script won't really
DO anything. After all, a shell script is really just a bunch of common commands put in order in one group to save on typing (although they can be full out applications).
Functions: are really just scripts within scripts. In any large script the base script only holds one or two calls/commands, which in turn make the functions do all the real work. Functions help to organize common and/or like commands.
Variables: are also (like functions) not just wanted, but in some cases required. Variables store data for the user to be used later and/or more than once.
First, before we actually write a quick and easy "hello world" script. You need to know some of the requirements for the scripts interpretation (since scripting is really an interpreted language and not compiled). At the very top of the script you must specify which shell will be used to read the script file. Since this tutorial is only geared towards BASH the top line in every script will be:
Code:
#!/bin/bash
This first commented line explains which shell the script needs in order to run properly. All comments must start with a
#.
I think it's time to get started actually writing a script. For this scripts we will be using the
echo command. The
echo command will always exit out to the next line on your command line (unless the
-n tag is used). In your favorite text editor type:
Code:
#!/bin/bash
echo hello world
Save the file as
first_script and open a terminal window. Navigate to the directory where you saved the script, and make the script executable:
Code:
chmod u+x first_script
Now you can run the script by typing:
Code:
./first_script
Your terminal window (console) should look similar to the following:
Code:
user@host:~$ chmod u+x first_script
user@host:~$ ./first_script
hello world
user@host:~$
If you received no errors in the above example, pat yourself on the back, you just created a shell script.
Now we are going to play a little with
echo. Create a new file called
echo_fun. In that file write:
Code:
#!/bin/bash
echo i am on one line
echo i am
echo on two lines
echo -n i am
echo on one line
Notice on the above example that the output of the last echo command ran two words together, am and on. It's always best to use quotation marks (
"") to keep that error (or similar) from happening. Let me give you a few examples of errors that can happen if you don't use quotation marks in the
echo command. In the script you just wrote (
echo_fun) change all the lines from
i am to
i'm. Then run it again. Did it error? Of course, it's missing a closing quotation mark. BASH sees single (
') and double (
")quotation marks as very similar things. If you have to output the actual single quotation marks (or apostrophes) use double quotation marks around the data, otherwise it is quite safe to use single quotation marks. I personally (because it's easier to stick to one thing) always use double quotation marks (unless i'm quoting something). Let's see what exactly I mean.
Let's make a new script file called
single_double. In it have the following lines.
Code:
#!/bin/bash
echo "i am using double quotes"
echo 'i am using single quotes'
echo "i'm using double quotes to show my single quote or apostrophe '"
echo '"i am using single quotes to show my double quotes as a quoted statement"'
Looks confusing I'm sure. The easiest way to explain it, if you have a single quotation mark or apostrophe, you have to surround it with double quotation marks and visa versa. Just remember that when using
echo, if you use an apostrophe, you must surround it with quotation marks.
Now that you have the basics of
echo accomplished. Let's start using some variables. If you don't have any programming background, variables are
containers (like a glass) that hold
data (like water). Luckily, in shell scripts, we don't have to tell the shell what the variable is holding (like most programming languages). BASH doesn't care if the data is an integer, character, string, float, or any of the other basic (normal) variables. Infact, you don't even have to
declare (tell the computer that it exists) the variable before you use it in BASH scripting. All variables start with a
$. The variable
bob is written
$bob when you are referring to it. Here's an example (from here on out I leave it to you to name the file and make it executable):
Code:
#!/bin/bash
bob=hello
echo "$bob"
When you run that you would get the following output:
Code:
user@host:~$ ./var_hello
hello
user@host:~$
Now edit the above file to read:
Code:
#!/bin/bash
bob=hello
echo "$bob world"
Run it and it should say (from here on out I will not show the command line, just the output):
Code:
hello world
As you may have noticed, the shell takes whatever you put for
bob and replaces
$bob with it word-for-word. Here's another example:
Code:
#!/bin/bash
bob=hello
jane=world
baby=" "
echo "$bob $jane"
echo "$bob$baby$jane"
As you can see, everything is taken very literally. If you have a space after a variable, the shell puts a space after the variable. BASH is literally taking whatever you placed inside of the variable. But what good are variables if the user can't put what they want inside of them? Do you as a programmer have to give only a few examples for the user to choose from? No. There is another fun command called
read. Let's see what it does shall we?
Code:
#!/bin/bash
# prompt the user to put in some data (notice the -n)
echo -n "Type your name here: "
read answer
echo "Your answer was $answer"
Run it. Pretty neat huh? But isn't that a bit much to get a variable populated? Can't it be done in one line of code instead of two? Yes,
read has a tag (
-p)
p for prompt. Want an example?
Code:
#!/bin/bash
read -p "Type your name here: " answer
echo "Your answer was $answer"
Notice it's the exact same thing. The first script is identical to the second, we just wrote it different. I only use the second example in day to day scripting. I feel that you should stick to doing things just one way. That way you can excel at that one way instead of spreading your abilities between many different things.
Not all variables are made by the scripter. Some variables are created by BASH. One such BASH created variable is an argument variable. If you call a script and pass it arguments, the arguments can be used within the script. Call this script
argTest Example:
Code:
#!/bin/bash
echo $1 $2
Now run the script with whatever two arguments you want, like
argTest hello world Or like
argTest me Tarzan! Point is,
$1 and
$2 are replaced with whatever you
pass to the script. Now that you have a vague understanding of how to pass arguments to a script, I think you can get a vague understanding of functions. Here is an easy example of a script using a function.
Note: Functions must be written before they are called within a script.
Here is an example of a hello world script using a function.
Code:
#!/bin/bash
function sayHello
{
echo $1 $2
}
sayHello Hello World
I'm sure by now you can guess what the output will be. The Beginner portion of my scripting tutorials is almost done. I hope after having read this one, you have a very good idea of the inner workings of a shell script. I havn't gone over any logic tactics (use of if/then and loops) yet because I don't feel they are important for basic shell scripts. Considering a basic shell script is really just a file with multiple commands within it that the shell executes in order of appearance. Let's write one more script that will hopefully incorporate all the lessons above into one nifty little script. I think this script will make the user change directories to one that is passed to the script and once there, it will create a file named
file_bob. Once it creates the file it will then list the contents of the directory and prompt the user to enter the directory in which to goto after the above steps are completed. Whew...that's alot....here goes:
Code:
#!/bin/bash
# write a function that creates the file
function fileMaker
{
# show the present working directory
pwd
# create the file using touch
touch $1
}
# write a function to get the final destination directory
function newDir
{
read -p "Please enter the directory you wish to be in: " DIR
}
# change directories to the one passed when calling the script
cd $1
# call the fileMaker function with an argument
fileMaker file_bob
# list the contents of the current directory
ls
# call the function newDir
newDir
# change to the directory that the user specified in the function just called
cd $DIR
Sounded like alot, but once you look at it, it's really not that much coding. It's mostly comments. Here is the same script without the comments:
Code:
#!/bin/bash
function fileMaker
{
pwd
touch $1
}
function newDir
{
read -p "Please enter the directory you wish to be in: " DIR
}
cd $1
fileMaker file_bob
ls
newDir
cd $DIR
I think this concludes my Basic BASH Shell Scripting Tutorial. If you take what you learned above, you can apply it to many different commands in many different patterns and create many different useful shell scripts. If you want to see how easy it is to make a fully functional shell application, wait for my intermediate tutorial. Hope this proved to be a useful learning experience.