Yes, there’s a Part III!
You’re going to have to start scripting and now that you know a few VI/VIM commands, lets talk beginning scripting with shell.
In our example below, we’re going to start a new project called “test”. For this, the requirements are:
- create a new folder off of the /u01/scripts directory
- create a new file called test.sh inside the testdir directory
- ensure it uses bash as our chosen shell
# cd /u01/scripts # mkdir testdir # cd testdir # touch test.sh # ls test.sh # pwd /u01/scripts/testdir
As you can see, I’ve now fulfilled the first two steps of the requirements. Now I need to edit the new file I created and add the shell to be used.
# vim test.sh i<enter> #!/bin/bash :wq<enter>
What I did in the above steps was to:
- open the file I created with the touch command in VIM.
- hit “i” to insert
- Add the dialect of shell scripting that we want to use. By adding the “#!” before the path to the correct shell program, this tells the script to execute /bin/bash <filename>
- hit :wq” to write and quit the file, returning to the prompt.
This is the very beginning of scripting with shell. We’re not going to go any further with this, but actually clean up, (aka remove) what we just did and how to do that properly. From the /u01/scripts/testdir path:
# rm test.sh # ls # cd .. # rmdir testdir
For our next example, let’s say there are more files than the test.sh file in the directory:
# ls test.sh test1.log test1.sh test2.log test2.sh
Now the rmdir, (remove directory) command won’t work. You could use the command at the /u01/scripts path location to remove the testdir directory and ALL the files within it:
# rm -rf ./testdir<enter>
This is a destructive command, removing testdir and all files below, but what if you were really supposed to keep those other files or forgot to put in a directory name?
# rm -rf .<enter>
Well, that’s not what you wanted to do…. Its important to always double check the command before you hit the enter key and also consider scripting destructive commands that you have to run on a regular basis to deter from catastrophic mistakes.
Also published on Medium.