I need to call another shell script testarg.sh within my main script. This scri开发者_如何学Cpt testarg.sh has arguments ARG1 ,ARG2, ARG3. I need to call up the below way:
./testarg.sh -ARG1 <value> -ARG2 <value> -ARG3
ARG1 and ARG3 arguments are mandatory ones. If it's not passed to the main script then I quit. ARG2 is an optional one. If the ARG2 variable is not set with value or it's not defined then I need not pass it from main script. So I need to call up the below way
./testarg.sh -ARG1 <VALUE1> -ARG3
If the value exist for the ARG2 Variable then I need to call the below way:
./testarg.sh -ARG1 <VALUE1> -ARG2 <VALUE2> -ARG3
Do I need to have a if else statement for checking the ARG2 variable is empty or null? Is there any other way to do it?
Amendment
If ARG2 is set, then the call should be:
./testarg.sh -ARG1 -OPT2 $ARG2 -ARG3
If this is in bash, you can write
./testarg.sh -ARG1 $ARG1 ${ARG2:+-ARG2 $ARG2} -$ARG3
The construct ${param:+word}
evaluates to word
if param
is set, or nothing otherwise. So if $ARG2
has a value, you get -ARG2 $ARG2
, otherwise nothing.
#!/bin/sh
if [ "$1" = "" ]; then
echo ARG1 is null
else
echo ARG1 = $1
fi
if [ "$2" = "" ]; then
echo ARG2 is null
else
echo ARG2 = $2
fi
精彩评论