A new command can be created by writing a shell script. A shell script is just a text file containing a sequence of shell commands. Almost anything accepted at the command line can go into a shell script file. However, the first line is unusual; called the shebang, it holds the path to the command interpreter, so the operating system knows how to execute the file: #!/path/to/interp flags. This can be used with any interpreter (such as python), not just shell languages. Here is a simple example of a shell script:
#!/bin/sh STR="Hello world" echo $STR
Open a file, say hello.sh, and type in the commands shown above. Then save the file and set the executable bit as follows.
chmod +x hello.sh
Now run the script. Here is what it will look like.
[amit@onyx]: chmod +x hello.sh [amit@onyx]: hello.sh Hello world [amit@onyx]:
As it stands, hello.sh only works if it is in your current directory (assuming that your current directory is in your PATH). If you create a shell script that you would like to run from anywhere, then move the shell script to the directory ~/bin/. Then you will be able to invoke the shell script from anywhere since that directory is on the shell PATH.
Don't forget that shell scripts need to be set executable - chmod +x <script>. Also, it is not a good idea to name your script test - there is a built in by the same name, and this can cause no end of debugging problems. Similarly, it is usually a good idea (for security) to use the full path to execute a script; if it is in your current directory, then ./script will work.
Finally, for debugging scripts, bash -x script will display the commands as it runs them.
Frequently, you will write scripts by entering commands on the command
line until things work. Then, you open an editor and retype all the
commands. However, you can use the history mechanism to your advantage:
recall that history will display the history file, and fc will
load selected commands into the editor. However, fc <first> <last> will
load the lines from the <first> command to the <last> command
into your editor. Simply make your edits, and write them to a new file.