Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
8 CHAPTER 1 Introduction to command shell scripting BASH BASICS We need a few basic items to get started with our first bash script, the traditional Hello World. We first need an environment with a bash shell. As we discussed throughout the chapter so far, we will be likely to find bash present on most UNIX and Linux distributions, as well as OS X. We may also find bash on Windows in some cases, a topic we will return to later in this chapter. For ease of use and consistency, we will use the bash shell on the BackTrack Linux 5 2 distribution, as we covered in this book's Introduction. Second, we need a text editor. A number of text editors are perfectly suited for creating shell scripts, from text-based editors such as vi and Emacs, to graphical editors such as Kate. Which editor to use is really a matter of personal preference, but for sake of use we will stick to Kate, as shown in Figure 1.3, for the rest of our bash discussions. Hello World We will jump right into the script, then go back through and examine the lines we have entered. Open a new file in Kate, and enter the following: #!/bin/bash echo "Hello World" Now we want to save the file somewhere convenient, such as the root of our home directory, or on our desktop. We can do this in Kate by clicking File and then Save, navigating to where we want to save the file, inputting a name in the Location field ( helloworld ), and then clicking Save again. In order to run the script we just created, we need to make it executable. We can do this by issuing the command chmod u+x helloworld from the command line while we are in the directory containing the file. This command will add execute permissions for the user that owns the file. Now that we have created the file and made it executable, we simply need to run it. We can do this with the command ./helloworld . The ./ in front of the command tells the shell we should be executing the script in the current directory, not any other scripts or commands named helloworld that might exist elsewhere in the file system. If everything went well, we should see output similar to Figure 1.4. Briefly stepping through what we did, the first line in our script dictates to the operating system how exactly we want it to interpret everything that follows. The line #!/bin/bash is composed of two parts. The first part, #! , is known as a shebang, and tells the operating system that the next thing on this line will indicate what we would like it to use as an interpreter for our script, in this case /bin/bash , the bash shell. It is possible that bash is located elsewhere in the file system, and we can determine its location by running which bash . The second line, simply enough, says to print the string Hello World . 2 www.backtrack-linux.org/downloads/