A shell script is nothing more than a list of commands for Unix to execute. To write a shell script, you’ll
1. | Open your favorite editor and start a script file. |
2. | Start the shell script with #!/bin/sh. |
3. | Add the shell script code one line at a time. This code will look strangely familiar— it’s similar to code you’ve already used in this book. |
4. | Save and close the file. |
In the following steps, we’ll show you how to try out this process by writing a script that prints three lines onscreen (Figure 10.1). Yeah, we know—whoopee!—but you have to start somewhere, and you can apply the same principles to other shell scripts you create.
1. | pico myscript For starters, access the editor of your choice and start a new file. In this case, we call it myscript. | |
2. | #!/bin/sh On the first line of the script, enter #!/bin/sh, which specifies the complete path to the shell that should run the script. | |
3. | # this is my first shell script On the next line, type a # (to indicate a comment), and then add any other notes you want to make. It’s always a good idea to use extensive comments in your scripts to help you see what’s going on. Remember, comments are for your reference only and won’t show up onscreen or do anything. | |
4. | echo friendsjustfriends On the next line of the script, type echo followed by the text you want to see onscreen. Here, echo tells Unix to display friendsjustfriends onscreen—a message just between friends. Code Listing 10.1. Using echo options, you can get good under standing. Or, perhaps, a good understanding just between friends.
| |
5. | echo Add another line with echo and nothing else to display a blank line. | |
6. | echo "standing" Add another echo command. Note that if you use leading spaces or tabs, as we’ve done here, you must use quotes, as Figure 10.1 shows. | |
7. | echo -e " good" Using the -e flag plus , you can insert a tab character. See Getting Fancy with echo for more echo options. | |
8. | ||
9. | sh myscript Use sh myscript to run your new script. In doing so, you get good under standing (literally), as shown in Code Listing 10.1. Ta-daaaaa! You just wrote your first shell script! (See the following section for more information and details on running scripts.) |
✓ Tip
Unless you have some compelling need to use a different shell (for example, if you’re taking advantage of functions that exist only in zsh), just stick with sh for your scripts for now.