Parameter checking in scripts

Hi,I need to write a script which performes some action on files which are 4 weeks old (no parameters specified), unless another timeframe is specified (in parameter $1).I can't figure out how to check if $1 is specified or not.Any help appreciated.Pete.

Re: Parameter checking in scripts

Hi Peter

see:man ksh(1) Section "Parameter Substitution."

<...> ${parameter:=word} If parameter is not set or is null, set it to word; then substitute the value of the parameter. Positional parameters cannot be assigned in this way.<...>my be what you're searching for.

Re: Parameter checking in scripts

Thanks all for the quick replies.James's solution seems elegant. But when I run this script with parameters it gives correct output. Running a 2nd time without parameters it gives the same output as the 1st run.Somehow it seems to conserve the parameters???

Re: Parameter checking in scripts

Hi (again) Pete:

Well, that's quite impossible for the script to retain state between executions. I suspect that your terminal settings are to blame. I suspect that you ran the script with arguments; recalled the command line; and "backspaced" over the arguments. If the backspace truly didn't erase, then you would see the behavior you did.

Re: Parameter checking in scripts

Peter,

Yes your are 'sourcing' the script instead of simply running it.Is that deliberate? (why?)What shell are you in while executing this?Did you use the exact script as provided, or did you already augment it?This does not reproduce for me.

From the Posix shell man page: "The dot (.) special command, as in . file, reads the entire file before any commands are executed. Therefore, alias and unalias commands in the file will not apply to any functions defined in the file."

Re: Parameter checking in scripts

As James points out, 'sourcing' a script means that the current shell remembers any variables that are previously set. So to allow for maximum flexibility, you should always test for the quantity of parameters passed to the script and ignore anything in the variables if the quantity is not correct (or in your case, preset the default values):

#!/usr/bin/shset -u

[ $# -eq 1 ] && VAR1=$1 || VAR1=4

echo "VAR1 is $VAR1"

In this case, the test is explicitly for one parameter so anything else (ie, no parameters, two parameters, etc) will leave VAR1=4, otherwise, VAR1 is assigned the first parameter on the command line. As with all interactive scripts, you should assume that monkeys are typing on the keyboard and the value for VAR1 should be tested for validity (ie, not a number, number too large or small, etc)