Suppose you create a script that will automatically run when you log in each day. The script might, for example, print “Greetings!” onscreen and possibly deliver a cle(a)ver message: “Say, you’re looking sharp today!” You could easily do this with the information you’ve learned so far in this chapter.
What would be handy here would be to add a line to the script that tells Unix to do all those things plus name the most recently used file—for those of you who need a reminder about what you were last working on. You could just use an ls command, but that would only list the filenames and not integrate the information with the rest of your morning greeting. Instead, a better (and more attractive) idea would be to bundle a couple of commands and use them with echo (Figure 10.4) to embed the information right into the greeting.
1. | vi myscript To begin, open myscript or another script in your favorite editor. Your script might look like Figure 10.4, with the greeting onscreen.
| |
2. |
echo "You were most recently working"
→ on `ls -1Fc ~/ | head -1`."
Type echo followed by the descriptive text you want to see. Then embed the ls command (`ls -1Fc ~/ | head -1`) within the descriptive text. Note that the embedded code begins and ends with ` before . (dot). The embedded command here lists just the most recently changed file or directory in the home directory. 1 provides for one entry per line, F formats the directory names with a / so we can tell whether we’re working in a subdirectory or on a file, and c sorts by the modification date. We then pipe the output to head -1, which displays the top line of the file. | |
3. |
✓ Tips
You can embed dates into scripts, too. Try echo -e “Today is `date +%A`” if you work so much that you forget what the day of the week is. See the sidebar Using Clever Dates for more date details.
When you embed commands that are directory-dependent—such as ls or find— be sure to specify the complete path. If you don’t, you’ll get paths relative to where the script is rather than relative to where you’re running the script from.
Embedded commands are useful in many ways. You can use them anytime that you want to have one program act based on the output of another program, just as echo displays something based on the output of a program.
[ejr@hobbes scripting]$ myscript
Greetings! Say, you're looking mighty
sharp today!
You were most recently working on figlet.
[ejr@hobbes scripting]$
|
3.149.233.72