A script on AIX which checks the number of parameters passed and complains if they are not correct:-
if [ "$#" -ge 1 ]; then ... else echo 'Usage: myscript <a> [b] [c]' fi
The script sets some environment variables so it is sourced. By that I mean I type the following on my command line. There is no second script, I am not sourcing a script from within another script.
If I pass it no parameters, I expect it to print out the usage statement but instead it runs using the parameters passed to the previous command that was sourced (not necessarily even this script!).
To double check this I added this line at the beginning of my script to prove that this was the case.
echo $# $@
If I pass it no parameters, it prints out the number and the list of parameters from a previously sourced script.
How do I get it to say
$# is zero when I pass it zero parameters and source it?
The smallest possible recreate is a script thus:-
echo $# $@
and then run it thus:-
. ./myscript.sh a b c
which prints out
3 a b c
then run it again without any parameters thus:-
which prints out the same
3 a b c
when you would expect it to print out
If you don't source the script and just run it thus:-
then it works as expected and prints out
I hope that clarifies the issue at hand.
Since I seem to be getting lots of answers to explain why the above doesn't work and no answers to tell me what I should do instead, I thought I would have one more attempt at trying to explain what I am trying to do.
I need to write a script that expects at least one parameter and complains if it is not invoked with a said parameter (see the first block of code in my question above), and this script needs to set some environment variables. Because of this second requirement I have assumed that I need to source the script so that the environment variables are still set when the script completes. How can you write a script that can tell when it has not been passed parameters that is also able to set an environment variable?