Tips on Writing Shell Scripts
- Use "stepwise refinement", which means to work on your program in
steps. Make sure each part is well tested before moving on to the next step.
- Us command-line editing.
- Since most of you use vi as your
editor, I recommend using it to access your history and edit your commands.
(You may use emacs or pico if you prefer.)
- After logging in, type the following:
set -o vi
Note: this is the only way to set up in some versions of bash. You must type this in at
the command-line each time you log in.
Having it in a shell script (for instance your profile) does not work in all
versions of Linux. We will try it in yours and see what happens.
- Using command-line editing will let you bring up your previous commands
with
<ESC>- or <ESC>k
Keep pressing k (or -) to move back through your commands.
- You can also search for a previous command with
<ESC>/regex
- Once you have a command up, you can edit it using vi commands.
- You can use any commands that work on the current line.
For instance use w to move to the next word,
fp to move to the next p in the line,
xp to reverse two characters,
dw to delete a word, ...
- Once you are ready to execute the new command, simple press Enter.
- You can also execute a command while you are in vi with !.
- In vi, the % is used to mean "the current file".
- So, if you forgot to set the permissions on the shell script you are editing, you can
set it without getting out of vi.
Type:
:!chmod 700 %
(then press Enter) to give it rwx for the owner (you).
- To run the shell script from inside of vi, type:
:!%
- If you want to pass in any arguments, add them after the %. For instance,
this:
:!% arg1 "argument 2"
runs the current file with two arguments.
- To re-run the previous command, type:
:!!