- Unix Shell Scripting
- Shell Basics
- Testing in bash
- Capturing User Input
- Scripting : Exercise 1
- Bourne/Bash/Korn Commands
- Shell Variables
- IO Redirection
- Operators, Wildcards and Expressions
- Flow Control
- Scripting : Exercise 2
- Shell Differences
- String Functions
- Power Tools
- Exercise 3
For our first trick, we’re going to write a script that shows us how arguments are dealt with by scripts. Start a new script called args. (Notice that it doesn’t have to be “args.sh”.)
Create the script:
#!/bin/bash if [ $# -lt 1 ] ; then echo "You must pass at least one argument." exit 1 fi
Save it, chmod it, and test it by calling it with zero, one and multiple arguments.
Count and echo arguments by adding these lines to the file:
echo "You passed $# arguments." echo "They are: $*."
Once again, save and test. Try at least one argument that contains one or more spaces. What happens with that argument?
Now add these lines to echo each argument on a separate line:
for x in "$@" do echo "$x" done
Usual routine: save and test. Again, use at least one argument containing spaces. How does this script handle them now?
Assume you will need a script to rotate your log files. The main log is users.log.
Also assume you will keep old log files named users.log.1 through users.log.5. They will live in in /var. DON’T CREATE THEM DIRECTLY. Do it in the script.
Write a new script that renames file users.log to users.log.2, and so forth, and deletes or overwrites the oldest log.
Name it rotate.
Make sure it is executable.
You can use this procmail rotation script as a model:
# Rotate procmail log files cd /home/studenth/Mail rm procmail.log.6 # This is redundant mv procmail.log.5 procmail.log.6 mv procmail.log.4 procmail.log.5 mv procmail.log.3 procmail.log.4 mv procmail.log.2 procmail.log.3 mv procmail.log.1 procmail.log.2 mv procmail.log.0 procmail.log.1 mv procmail.log procmail.log.0
Now update your script to take an argument, rather than a hard-coded name, for the log names.