views:

38

answers:

2

I need to call another shell script testarg.sh within my main script. This script 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
A: 
#!/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
zed_0xff
Missed out while posting earlier if ARG2 has a value then i require ./testarg.sh -ARG1 -OPT2 <$ARG2> -ARG3 If ARG2 doesn't have a value then i require ./testarg.sh -ARG1 -ARG3
Arav
That doesn't help much with the invocation of the sub-script.
Jonathan Leffler
Thanks a lot for the info
Arav
+3  A: 

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.

David Zaslavsky
It's a korn shell. will it work
Arav
Missed out while posting earlierif ARG2 has a value then i require ./testarg.sh -ARG1 -OPT2 <$ARG2> -ARG3If ARG2 doesn't have a value then i require ./testarg.sh -ARG1 -ARG3
Arav
Yes, Bourne, Korn, POSIX, Bash shells all support the notation.
Jonathan Leffler
And you can do; `./testarg.sh -ARG1 ${ARG2:+-OPT2} $ARG2 -ARG3`.
Jonathan Leffler
@arav: you can edit your question to add the extra detail, rather than replicating a comment around the answers.
Jonathan Leffler
Thanks a lot for the info.
Arav