shebang"> ]>
Bash Scripting Introduction HOWTO FrancisLitterio
franl@world.std.com
RohitPatil
rvpatil@gmail.com
2004 Francis P. Litterio, Jr. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation A copy of the license is included in the section entitled "GNU Free Documentation License" (). 2004-XX-XX 1.0 2006-XX-XX FL RP First release in Docbook format. Based on an earlier version in Linuxdoc format by Mike G. This HOWTO helps you write basic Bash shell scripts. This HOWTO assumes that you know nothing about shell scripting, but it assumes you have used Bash or the Bourne shell interactively. You do not have to be a programmer to benefit from this HOWTO. This is not an advanced shell scripting HOWTO. If you want to read an advanced document on this topic, see The Advanced Bash-Scripting Guide at the &ldp; (&ldpurl;).
Introduction Where to Find This HOWTO You can always find the latest version of this HOWTO at the Linux Documentation Project at this location:
&thisurl;.
Overview The Bourne Again Shell (Bash) is the primary shell of the GNU system. It is compatible with the Bourne shell, which is one of the oldest UNIX shells, but it has many enhancements that make it superior to the Bourne shell. A Bash script is a human-readable file containing commands that are executed by Bash. This HOWTO is an introduction to writing Bash scripts. This HOWTO is written for anyone who wants to begin writing Bash scripts but who has no prior scripting experience. You do not have to be a programmer to benefit from this HOWTO, but you need to have some experience using Linux (or any UNIX system) from an interactive shell, preferably Bash or the Bourne shell. If you are a C shell user who has never used a Bourne-like shell, some of the Bash commands may appear strange, but this HOWTO should still be valuable to you. Disclaimer No liability for the contents of this document can be accepted. Use the concepts, examples and information at your own risk. There may be errors and inaccuracies in this document that could lead to damage to your system. Proceed with caution, and although damage to your system is highly unlikely, the author(s) do not take any responsibility for damage or loss caused by errors in this document. All copyrights are held by their by their respective owners, unless specifically noted otherwise. Use of a term in this document should not be regarded as affecting the validity of any trademark or service mark. Naming of particular products or brands should not be seen as endorsements. Credits and Contributors This document is based on an earlier version written by Mike G. The following people contributed to this document in one form or another: Nathan Hurst Jon Abbott Felix Hudson Kees van den Broek Andreas Beck Feedback Feedback is welcome. Send your comments to the author. Translations There are currently no translations of this document into other languages. If you would like to provide one, please contact the author.
Getting Started What You Should Already Know This HOWTO assumes you know the following things about using Bash interactively. You understand the purpose of the Bash startup files .bash_profile and .bashrc in your home directory, even if you have not edited them yourself. For more information on Bash startup files refer to the man page for Bash on your system, which is usually found by running the command "man bash" or "man bash | less" for a more navigable man page on Solaris. You understand the purpose of the environment variables HOME and PATH. You understand the purpose of basic shell metacharacters, such as "*", "?", and "~". You understand how to run commands in the background by appending a "&" to the end of a command. What and Where is Bash? Bash is a shell, which is a program that reads commands and executes them. Sometimes, the commands that Bash reads come directly from the keyboard as you type them. When this happens, we say that Bash is an interactive shell. If you've ever logged into a UNIX system, then you've used an interactive shell. Bash is the default interactive shell of the GNU/Linux system (and you might also find it installed on commercial UNIX systems). Sometimes, the commands that Bash reads come from a file called a shell script. When this happens, we say that Bash is a non-interactive shell. In this case, Bash reads each line of the script file from top to bottom, executing each command as if it had been typed on the keyboard. Where is the Bash shell? On GNU/Linux systems, you'll always find Bash in /bin/bash. On commerical UNIX systems, such as Solaris or HP-UX, you might find it in the same place, or it might be in /usr/local/bin/bash. You rarely need to run Bash directly, but you need to know where Bash is located on your system so that you can write the very first line of your Bash scripts correctly. Often, you can find where Bash is located on a UNIX system by typing "which bash" or "type bash" to your interactive shell. If that doesn't work, try this find command (but beware that it may take a while to complete):
find / -type f -name bash 2>/dev/null
If you are running the C shell (csh), you might find Bash by typing "whereis bash". If that doesn't work, ask your system administrator or local guru for help. It's possible that you do not have Bash installed on your system. If this is the case, you'll have to download the source code for Bash, build it, and install it. If you've never done those things, ask your system administrator or local guru for help. It's not hard to do.
Writing a Simple Bash Script Let's start with a simple Bash script and work up to more complex ones later. Just about the simplest program you can write in any programming language is a Hello World program, which is a program that simply outputs the text "Hello world". shows a Bash script to do that.
A Simple <emphasis>Hello World</emphasis> Script #!/bin/bash echo Hello world
shows a very simple two-line Bash script. Create this script by typing those two lines into a file using your favorite text editor. The name of the file can be anything you choose, but you should not name the file test, because there is a built-in test command in almost every shell, and it's too easy to accidentally run the built-in test command instead of your own script. I suggest that you name this script hello. Be careful to type the script exactly as you see it in . If you misspell a word or mistype the first line, the script may not work. One common mistake is to put a space somewhere on the first line. There should be no spaces anywhere on the first line. Another common mistake is to put one or more blank lines above the line containing "#!/bin/bash". That line must be the very first line of the script.
Running the <emphasis>Hello World</emphasis> Script Once you've created your Hello World script, you can execute it in a variety of ways. Let's assume that you named the script hello, and it exists in your current working directory. shows how to execute the script. In this example, the interactive shell's prompt is shown as "bash$". Your shell's prompt might look different, but that's OK.
How to Run a Bash Script bash$ bash hello Hello world
When you type "bash hello" as shown in , if you get an error message that says "command not found" (or something similar) then either you don't have Bash installed on your system or it is installed in a directory that is not listed in the value of your PATH environment variable. If you get an error message that says "No such file or directory", then your current working directory is probably not the one containing the script you just created. The command "bash hello" starts a non-interactive Bash shell and passes it one argument: the name of the file containing the script to execute. While the script is running, there are actually two shells running! One is the interactive Bash shell which displays the "bash$" prompt and executes the command "bash hello". The other is the non-interactive Bash shell that you manually started to execute the script. The interactive shell isn't doing anything while the script is running — it's merely waiting for the non-interactive shell to terminate. In , the interactive shell is Bash, but you don't have to use Bash as your interactive shell to run a Bash script. The command shown in will work no matter which interactive shell you use. It's a bit of a hassle to run Bash scripts this way. It would be simpler if you could just type the name of your script without the leading "bash" to make the operating system automatically start a new Bash shell to execute your script. That way, the script can be run just like any other program. To allow your script to be run without having to type the leading "bash", you must do two things: Change the permissions on the script to allow you to execute it. This can be done with the command "chmod u+x hello". You don't have to grant execute permission just to yourself. The command "chmod ugo+x hello" allows everyone to execute your script. See the man page for the chmod command for more information. Make sure that the directory containing the script is one of the directories listed in the value of your PATH environment variable. A good way to satisfy the requirement in item # above is to do this: Create a directory named "bin" under your home directory. You can do this with the command "mkdir $HOME/bin". Move the script to that directory. You can do this with the command "mv hello $HOME/bin". List the full pathname of that directory in the value of your PATH environment variable (We cover variables in more detail in ). You can do this by putting the following line into your interactive Bash startup script (which is the file .bashrc in your home directory):
PATH="$HOME/bin:$PATH"
Terminate your shell, and start a new one. You have to do this because the changes to your .bashrc file only take effect in shells started after you save the changes.
Lastly, if you don't want to permanently alter your PATH environment variable (as shown above), you can run a Bash script in your current working directory by typing "./scriptname". If you want to run your scripts in this fashion, you still have to make the script executable using the chmod command shown above. shows how you can run your hello script if you have made the script executable.
Other Ways to Run a Bash Script bash$ chmod u+x hello bash$ ./hello Hello world bash$ mkdir $HOME/bin bash$ mv hello $HOME/bin bash$ PATH="$HOME/bin:$PATH" bash$ hello Hello world
shows both the "./hello" form of the command and the "hello" form of the command. The latter only works if hello is located in a directory that is listed in the value of your PATH environment variable. In the above example, the value of PATH is changed interactively so that it contains the pathname of the bin directory under your home directory, but to make that change permanent, you should edit your .bashrc as described above and restart your shell.
Understanding the <emphasis>Hello World</emphasis> Script Let's understand how the script shown in works. It's just two lines long, but both lines are significant. Neither line can be left out. The first line (#!/bin/bash) tells the operating system which shell to spawn to execute this script. Unlike programs written in compiled languages, such as C, Pascal, or C++, a Bash script is interpreted, which means that some other program (the interpreter) must read the script and execute the commands in the script. Bash is the interpreter for a Bash script. A good analogy is to think of a chef cooking a meal by reading a recipe. In this case, your script is the recipe, and Bash is the chef. The first line of your script must specify the full pathname of the Bash shell immediately after the characters "#!". If your Bash shell is installed somewhere other than /bin/bash, then you must know where it is installed and write the first line of your script accordingly. If you are using Linux, then Bash is always installed in /bin/bash. The first line in a shell script is sometimes called the shebang line. This term is derived from the use of the word "bang" to refer to an exclaimation mark and the fact that the first line of a shell script names a shell. The second line of the script in is an echo command. You typically use this command in an interactive shell to view the value of variables (we'll cover variables in ). In a Bash script, the echo command is the general purpose mechanism for producing output. It simply outputs its arguments to the terminal on which the script is running. A single space is output betwen each argument, and a newline character is appended. In general, Bash executes the commands in a script from top to bottom, executing each command as if it had been typed into an interactive shell. You can put any command in a Bash script that you would normally type to an interactive shell, and it will work the same way (see for a short list of exceptions to this rule). But what about that &shebang; line (#!/bin/bash)? What happens when Bash reads and executes that line? The answer is: nothing. The text between a "#" character and the end of the same line is a comment. A comment is completely ignored by Bash. You should use comments to make your script more readable by including information that helps the reader understand your script. We cover comments in more detail in . Since the "#!/bin/bash" line is ignored by Bash, why can't you leave it out? Although it is ignored by Bash, it is not ignored by the operating system, which uses the first line of the script to determine which shell to spawn to interpret the script. Thus, the first line of the Bash script shown in cannot be omitted, even though it is ignored by Bash. After Bash has executed the command on the last line of the script, Bash terminates, thus terminating your script. Later, we'll see how you can control when and how your script terminates. There is one situation where the &shebang; line isn't needed. If you run your script by explicitly invoking Bash, as shown in , then a &shebang; line isn't needed. However, you should always include a &shebang; line in your scripts, because you never know when you'll want to invoke the script like a regular command. Additionally, the &shebang; line acts to document the kind of script for human readers. Interactive vs. Non-Interactive Shells Before we move on to a more advanced Bash script, we should cover the few situations where the commands that you type into a Bash script work differently than the same commands typed into an interactive Bash shell. This is not a long list, but it is important to remember the following differences. If you have aliases defined in your personal .bashrc startup file, you cannot use those aliases in a Bash script. This is a good thing. Imagine that you could use your own personal aliases within a script. If you give that script to someone else, then it will malfunction, because the other user doesn't necessarily have the same aliases defined as you. That is why aliases are ignored by Bash when it executes a script. Aliases only work in interactive shells. In a Bash script, job control commands are not available. Specifically, after launching a background job by appending "&" to a command, you cannot use the bg, fg, and jobs commands to examine and manipulate the background job. You also cannot use the "kill %JOBID" form of the kill command to kill background jobs. This is not a great loss, since the job control commands were designed for interactive use, and they don't make much sense in a script. In a Bash script, if the exec command fails for any reason, Bash immediately terminates. This doesn't happen in an interactive shell so that you can try the exec command again. In a Bash script, you cannot use the history expansion character ("!") to execute previously executed commands. In fact, all command history functionality is disabled in a script (e.g., the history command is ignored). Comments A comment is any text following a "#" character on the same line, but the "#" character must be the first character in a word. Comments are ignored by Bash, but they help the person who reads the script to understand it. shows a script containing some comments. This is also the first script we've seen that contains blank lines. Bash ignores blank lines, so you can use them to make your script more readable.
Using Comments #!/bin/bash # This script is an example of using comments. echo Hello world # This comment shares a line with a command! # The next line does _not_ contain a comment! echo Hello#world # This is also a comment. The "#" doesn't have to be # in the leftmost column. Compare the next echo # command with the previous echo command. One little # space can make a big difference! echo Hello #world
The first line in the script shown in is the classic shebang line, described in . The comments should be fairly easy to see. The line that reads "echo Hello#world" contains a "#" character, but there is no comment on that line, because the "#" does not occur at the beginning of a word. The line that reads "echo Hello #world" contains a comment, because the "#" character occurs at the beginning of a word. As you can see from the output of this script, that line outputs only the text "Hello". When the above script executes, it produces this output:
Hello world Hello#world Hello
Some people think that writing comments in a script is a waste of time. Professional software engineers know this is not true. Software is hard to understand if you are not the author. Even if you are the author, it can be hard to understand long afterwards, when it isn't fresh in your mind. 20% to 50% of the lines in your scripts should be comments.
Using Quotes It is virtually impossible to write a Bash script without using quotes of one form or another. In a Bash script, the quote characters are: " (double quote) ' (single quote) ` (backquote) \ (backslash) Let's look at each one in turn. Double Quotes The double quote (") character is the simplest of the quoting characters. It is most commonly used to group space-separated words together so that Bash treats them as if they were one word. For instance, if you need to refer to a file that has spaces in its name, you can use double quotes, as follows:
cat "meeting agenda.txt"
In the above command, the cat program will be passed a single filename, meeting agenda.txt. Had the double quotes been omitted, the cat command would have been passed two filenames, meeting and agenda.txt. It's important to understand that the cat program receives this single argument:
meeting agenda.txt
Notice that there are no double quotes in the argument that cat receives, but there are double quotes in the command. Quote characters are metacharacters, which means they are removed by Bash before the command is executed. Even though metacharacters are removed, they are not ignored by Bash. In the above cat command, the double quotes change how Bash passes the arguments to the program, even though the cat program never sees the double quotes! Double quotes (and their cousins, single quotes and backquotes) must occur in pairs within a command. Unfortunately, if you accidentally use an odd number of double quotes in a command, Bash will not report an error. This happens because you can use double quotes to group words that span a newline character. Try this command in your interactive shell:
echo "This output occupies two lines"
When you press the ENTER key after typing the first line of that command, your interactive shell doesn't execute the command. Instead, it notices that you have not typed a closing double quote, and prompts you to continue entering the command. Only when a complete command — with a balanced set of double quotes — has been entered, will pressing the ENTER key execute the command. You can write the above command in a shell script too, and it will behave the same way. When writing a script, one common mistake is to leave out a closing quote. As a result, you end up quoting the remainder of the script -- perhaps dozens or hundreds of lines of code! Bash detects the error only when it reaches the end of the script and fails to find the matching quote. The error message will look like this:
scriptname: line 3: unexpected EOF while looking for matching `"'
The line number indicates the line on which the opening quote appears, so you won't have much trouble locating your mistake. Double quotes are also used to prevent Bash from giving special meaning to certain metacharacters. If you want your script to output an asterisk, you might attempt to do it with this command:
echo *
But the above command outputs the names of all files and directories in the script's current working directory, which is not what you intended. This happens because the asterisk is a Bash wildcard metacharacter, and Bash replaces each word containing an asterisk with a list of matching file and directory names before executing the command. You want Bash to treat the asterisk as if it were just an ordinary character — not a metacharacter. To do this, you use double quotes to escape (or quote) the asterisk as follows:
echo "*"
From now on, we'll use the more technical term escape instead of quote to mean using one metacharacter to remove the special meaning of another metacharacter. Let's be clear exactly which metacharacters double quotes escape. Double quotes escape the following Bash metacharacters. Wildcard characters: *, ?, [...] The home directory character: ~ Single quotes: '...' The background job creation character: & I/O Redirection characters: >, <, >>, <<, <<<, >&, and | From this list, you can see that the double quote metacharacter does not escape itself. What if you want to output some text surrounded by double quotes from a Bash script? In other words, how would you write a script so that the output of the script includes double quote characters? A command of this form doesn't work:
echo Now type "start-backup".
Try the above command in an interactive Bash shell. The double quotes do not appear, because Bash removes them before executing the echo command. Instead, you must escape the double quotes. That is, you must make Bash treat the double quote characters as if they are ordinary characters and not metacharacters. You cannot use double quotes to escape the double quotes, like this:
echo Now type ""start-backup"".
The double quotes in the above command are paired with each other in the order they appear. The two pairs of double quotes each quote an empty string. They are removed by Bash before the echo command executes. Instead, we need a different quote metacharacter. We need to use single quotes.
Single Quotes Single quotes are similar to double quotes, but they have a greater power to escape other metacharacters. Other than that one difference, single quotes are used just like double quotes. An advantage to having two different quote characters is that you can use one kind of quote character to escape the other, as shows.
Mixing Single and Double Quotes #!/bin/bash # This script shows how you can mix single and double # quotes, using one kind to escape the other kind. echo "'This text is surrounded by single quotes.'" echo '"This text is surrounded by double quotes."' echo "Welcome to Frodo's Place."
The output of the above script is:
'This text is surrounded by single quotes.' "This text is surrounded by double quotes." Welcome to Frodo's Place.
The above example shows that you need two different quote characters so that they can be used to quote each other, but there's another important difference between double and single quotes. Single quotes escape more metacharacters than double quotes do. In fact, single quotes escape absolutely every metacharacter, except themselves. shows how double quotes and single quotes escape metacharacters differently.
Differences Between Single and Double Quotes #!/bin/bash echo "My home directory is $HOME" echo 'My home directory is $HOME' echo "*" echo '*'
The output of the above script is:
My home directory is /home/franl My home directory is $HOME * *
As you can see, both single and double quotes escape the "*" metacharacter, but only single quotes are powerful enough to escape the "$" metacharacter (which is used to expand variables — we'll cover variables in ). Which metacharacters do single quotes escape? The answer is: all of them except for single-quotes. If you try to use a single quote in the middle of a single-quoted string, you end up with an odd number of single quotes, which is not valid Bash syntax.
Backquotes The fourth kind of quotes are backquotes: `...`. Backquotes have the same quoting properties as double quotes, but with one very big difference. The text between a pair of backquotes is executed by your shell and is then replaced by the output of that execution! shows backquotes in action.
Using Backquotes #!/bin/bash echo The current working directory is: `pwd` echo The current date and time is: `date`
The output of the above script is:
The current working directory is: /home/franl/examples The current date and time is: Thu Jan 30 20:43:42 EST 2003
You can put any valid Bash command inside backquotes. You can even put multiple commands separates by ';' characters inside backquotes. If you find you are writing a long sequence of commands within backquotes, you probably should create a separate shell script to contain those commands (or you might want to create a shell function, which is an advanced Bash scripting topic not covered by this HOWTO).
Backslash The third kind of quoting character is the backslash: \. The backslash is unlike the other kinds of quoting characters in that it does not occur in pairs. A backslash behaves exactly like the single quote, but it only escapes the character immediately following the backslash. shows an example of how to use backslashes:
Using Backslashes #!/bin/bash echo The price of the item is \$15.79 echo Welcome to Frodo\'s Place!
The output of the above script is:
The price of the item is $15.79 Welcome to Frodo's Place!
Variables A variable is a name for a place in memory where a shell script can store a string of characters. Those characters can be anything, including letters, digits, punctuation, spaces and tabs. In the following sections, we discuss how to assign values to variables and how to access those values after they've been assigned. Using Variables shows how to assign a string of characters to a variable.
Assigning a String to a Variable CARMODEL=Porsche
In the above example, the name of the variable is CARMODEL, and the string that is stored in the variable is Porsche. There must not be any spaces around the '=' character, and the string must be a single word. If the string contains any whitespace (i.e., spaces, TABs, or newlines), then it must quoted, as shown in .
Assigning a String with Whitespace to a Variable CARMODEL="Mini Cooper"
As discussed in previous sections, the quotes cause the string inside the quotes to be taken as a single word (as well as escaping various shell metacharacters). If there were no spaces (and no metacharacters that needed to be escaped) in the string, we wouldn't have needed the quotes, but it's good style to always use quotes when assigning a value to a variable. A variable's name must start with a letter or an underscore. The following characters can be letters, digits, or underscores. It is convention to write variable names in all uppercase characters, but that's not required. Here are some valid variable names: FIRST_NAME, LINE1, and _FILENAME. Here are some invalid variable names: 3rd_PARTY, MY-VAR, and INTEREST%. After you assign a string to a variable, you can access that string by writing the variable name prefixed with a '$', as shown in . This is called variable expansion.
Referencing a Variable's Value echo "The model of the vehicle is: $CARMODEL" OLDMODEL="$CARMODEL"
Notice that double quotes do not escape the meaning of the '$' metacharacter (but single quote will). If you want the variable expansion to be adjacent to other letters or digits, you need to use braces to mark the start and end of the variable name, as follows:
echo "There are 5 ${CARMODEL}s for sale." CARPLURAL="${CARMODEL}s"
If there had been no braces around the above variable name, the shell would have looked for a variable named CARMODELs instead of CARMODEL, and the script would have malfunctioned, because there is no variable named CARMODELs. A common task is to append (or prepend) a string to the current value of a variable. shows how to do each.
Appending and Prepending Text to a Variable's Value CUSTOMER_NAME="Fred" CUSTOMER_NAME="$CUSTOMER_NAME Smith" # Appends a string. CUSTOMER_NAME="Mr. $CUSTOMER_NAME" # Prepends a string. echo "$CUSTOMER_NAME" # Output is: Mr. Fred Smith
Kinds of Variables There are two kinds of variables: shell variables and environment variables. Shell variables are not inherited by child processes, and environment variables are inherited by child processes. Other than that one difference, they behave exactly the same. Why would you want a variable to be inherited by a child process? It's a convenient way to communicate information to a child process. Additionally, there are several common environment variables that many systems define for every user, such as HOME and PATH. Since those are environment variables in the initial login shell, every process descended from that shell inherits those variables. Built-in Variables Bash automatically defines several built-in variables that contain useful information. Whether or not you can assign new values to built-in variables depends on the variable. The Bash manual (&bashref;) lists them all, but here are a few: BASH_VERSION This variable expands to the current version of the Bash shell. You cannot assign a value to this variable. This is a shell variable. HOSTNAME This variable expands to the hostname of the computer on which the Bash shell is executing. You cannot assign a value to this variable. This is an environment variable. PWD This variable expands to the current working directory of the Bash shell (as it was last set by the cd command). You cannot assign a value to this variable. This is an environment variable. HOME This variable expands to the pathname of the home directory of the user who is running the shell. You can assign to this variable to change it temporarilly during a single shell session, but the next time you login, it will be set to its original value. This is an environment variable. There are many more built-in variables. See the Bash man page or the Bash Manual (&bashref;) for details.
Input/Output (I/O) Redirection It's almost impossible to write a non-trivial Bash script without using I/O redirection. Every UNIX shell, Bash included, provides I/O redirection, but the syntax differs between various shells. Naturally, we'll cover the Bash syntax. The Standard I/O Streams A running program is called a process. For example, your interactive shell is a process. When Bash reads a command (either from the keyboard or from a script), Bash spawns a new process to execute the command. Suppose Bash reads and executes the command "ls". The new process exists only for the time it takes the "ls" program to execute, and then the process terminates. When Bash starts a process to execute a command, the process is connected to several I/O streams. An I/O stream is like a hose that has one end connected to the process and the other end connected to a terminal. Data flows through an I/O stream like water flows through a hose. The data flows either from the process to the terminal (this is how the process produces output) or from the terminal to the process (this is how the process reads input from the keyboard). When a process first starts, there are always three standard I/O streams connected to the process: Standard input (stdin) Standard output (stdout) Standard error (stderr) Standard input is the name of the I/O stream through which a process reads input from its terminal. Standard output is the name of the I/O stream through which a process writes output to its terminal. Standard error is the name of the I/O stream through which a process writes error messages to its terminal. These standard I/O streams are sometimes referred to using their shorthand names: stdin, stdout, and stderr. Inheritance of I/O Streams When your Bash script is running, it is a process just like any other, so it also has these three standard I/O streams. The echo command writes its output to standard output. Standard output is usually connected to the terminal on which the script is running, so the output of the echo command typically appears on that terminal. It is possible to redirect an I/O stream so that it is not connected to the terminal but to a file. shows show you can change the hello script to redirect the standard output of the echo command to a file named xyz.
Redirecting Standard Output #!/bin/bash echo Hello world > xyz
In this example, the ">" is a metacharacter. The ">" tells Bash to temporarilly redirect standard output of the current command from its current destination (the terminal) to the specified file for the duration of the command. You can specify any relative or absolute pathname after the ">". In this example, the output of the "echo Hello world" command is redirected to the file xyz in the current working directory. Warning! If you redirect standard output to a file that already exists, the file is overwritten, destroying the previous contents of the file! Always be sure that you don't have any valuable data in the file that is going to be overwritten by redirection.
Conditionals Like all programming languages, Bash scripts can make decisions based on the values of variables and many other aspects of their system environment. A conditional is a statement that makes a decision. A conditional statement causes one or more other statements to execute or not depending on the answer to a question. Exit Status Every command executed by the shell has an exit status that is a number between 0 and 255. The exit status indicates the success or failure of the command. If a command's exit status is 0, it was successful, otherwise the non-zero exit status indicates which of many different errors occurred. The exit status of the last command that executed is stored in the built-in shell variable $?. shows some examples.
Examining the Exit Status of Commands bash$ touch newfile bash$ echo $? 0 bash$ rm newfile # This command succeeds. bash$ echo $? 0 bash$ rm newfile # This command fails: the file doesn't exist anymore. rm: cannot remove `newfile': No such file or directory bash$ echo $? 1 bash$ echo $? # Can you explain this output? 0
Notice the odd behavior of the last echo $?. Why does it output "1" the first time and "0" the second time? The reason is that the value of $? is always the exit status of the last command that executed. In (above), the second echo $? command outputs a 0 because the first echo $? command was successful. It's important to remember that any command alters the value of $?, so you only have one chance to access the value stored in $?. A common scripting practice is to store the value of $? in a shell variable so it can be accessed later, as shown in .
Saving the Exit Status for Later Use first_command STATUS=$? second_command echo "The first command exitted with status $STATUS."
The <command>test</command> Command *** UNDER CONSTRUCTION *** If Statements *** UNDER CONSTRUCTION *** The <computeroutput>&&</computeroutput> Operator *** UNDER CONSTRUCTION *** The <computeroutput>||</computeroutput> Operator *** UNDER CONSTRUCTION ***
Loops *** UNDER CONSTRUCTION *** While and Until Loops *** UNDER CONSTRUCTION *** For Loops *** UNDER CONSTRUCTION *** Where to Get More Information *** UNDER CONSTRUCTION *** Copyright and License This document, Introduction to Bash Scripting HOWTO, is copyrighted (C) 2002 by Francis Litterio. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". GNU Free Documentation License Version 1.1, March 2000
Copyright (C) 2000 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
PREAMBLE The purpose of this License is to make a manual, textbook, or other written document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup has been designed to thwart or discourage subsequent modification by readers is not Transparent. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. COPYING IN QUANTITY If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparent copy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has less than five). State on the Title page the name of the publisher of the Modified Version, as the publisher. Preserve all the copyright notices of the Document. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. Include an unaltered copy of this License. Preserve the section entitled "History", and its title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. In any section entitled "Acknowledgements" or "Dedications", preserve the section's title, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. Delete any section entitled "Endorsements". Such a section may not be included in the Modified Version. Do not retitle any existing section as "Endorsements" or to conflict in title with any Invariant Section. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections entitled "History" in the various original documents, forming one section entitled "History"; likewise combine any sections entitled "Acknowledgements", and any sections entitled "Dedications". You must delete all sections entitled "Endorsements." COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an "aggregate", and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entire aggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise they must appear on covers around the whole aggregate. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License provided that you also include the original English version of this License. In case of a disagreement between the translation and the original English version of this License, the original English version will prevail. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (c) COPYRIGHT-YEAR YOUR-NAME Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. A copy of the license is included in the section entitled "GNU Free Documentation License".
If you have no Invariant Sections, write "with no Invariant Sections" instead of saying which ones are invariant. If you have no Front-Cover Texts, write "no Front-Cover Texts" instead of "Front-Cover Texts being LIST"; likewise for Back-Cover Texts. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.