Creating a shell script is a matter of writing a text file containing valid commands and saving the text file. The script can then be run as an argument to the shell command or as a standalone executable file. Generally, you'll want to make scripts executable on their own.
To create a shell script:
1. | |
2. | For the script's first line, type the following: #! /bin/bash This is the complete path to the shell that should run the script. |
3. | For the script's next line, on general principles, type a pound sign (indicating a comment line) followed by a description of the script: # A baby script |
4. | Type the line that does the business of the script (it echoes text to the screen and rings the computer's bell): echo –e "Ring that bell! a" |
5. | Save the file as myscript. |
To run a script using the shell:
bash myscript
To make a script executable:
1. | Change the permissions on the script file to make it executable using chmod as explained in Chapter 11: for example, chmod u+x myscript |
2. | Check to make sure that the location of the script is on the path by comparing the output of the pwd and echo $PATH commands. If the script is not on the path, add it using the techniques explained in Chapter 10. |
3. | At the prompt, type the name of the script, myscript. The text will echo to the screen, and the bell will ring. |
Tip
You can use the contents of the history file, explained in Chapter 10, to turn your recent commands into a shell script by redirecting the last n lines of the history file to a script file, using a command like this: history 10 > myscript. This command functions pretty much as a macro recorder.
Tip
If your script isn't on the path, provided execute permissions have been set, you can start the script by using the dot operator: for example,. myscript.