Creating new commands

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. It is customary for shell scripts to have an .shextension but not required. Here is what it will look like.

[alice@onyx]: chmod +x hello.sh
[alice@onyx]: ./hello.sh
Hello world!
[alice@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. Create that folder if it doesn't already exist. This is typically where users store their own custom scripts. Then you will be able to invoke the shell script from anywhere if the ~/bin directory is on the shell PATH.

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.sh 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.