Passing parameter and option together


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Passing parameter and option together
# 1  
Old 05-31-2013
Passing parameter and option together

Hi ,

How can I pass option and parameter together?

I want like

Code:
script.sh par1 par2 -s option1

And when I am doing

Code:
echo $1
echo $2
#opt is the variable where we are storing the option value through getops
echo $opt

output should be
Code:
par1
par2
option1

This is needed because we already have a system which uses only parameters. Now the last parameter is optional. So It's hard to add extra optional parameter.
Also changing the current parameter to all option is not recommended because the client does not want to change all the existing cron entries fearing high risk in production.
# 2  
Old 05-31-2013
I'm not sure I understand the problem. You mention the solution yourself: the getopt command or the getopts builtin (bash).
# 3  
Old 05-31-2013
ok ...

Lemme clarify ..

for example with the below script

Code:
#!/bin/bash
  while getopts ":s:" opt; do
    case $opt in
      s  ) opt1="`echo $OPTARG| sed 's/^ *//'`"  ;;
    esac
  done
echo "opt1= $opt1"
echo "1st par: $1"
echo "2nd par: $2"


Case 1
command Line:
Code:
./script.sh -s 001

output:
Code:
opt1= 001
1st par: -s
2nd par: 001

But I need output as
Code:
opt1= 001
1st par: 
2nd par:

Case 2
command Line:
Code:
./script.sh "par1" -s 001

output:
Code:
opt1=
1st par: par1
2nd par: -s

But I need output as
Code:
opt1= 001
1st par: par1
2nd par:

Case 3
command Line:
Code:
./script.sh "par1" "par2" -s 001

output:
Code:
opt1=
1st par: par1
2nd par: par2

But I need output as
Code:
opt1= 001
1st par: par1
2nd par: par2

# 4  
Old 06-05-2013
The standards specify that options should come before operands; not after. There are ways to work around that, but I don't see any real reason to bend the guidelines for what you're trying to do. There are a couple of easy ways to deal with this. I've included sample code below for both of these.

The 1st way uses getopts the way it was intended and would be described in UNIX-like man pages with the SYNOPIS:
Code:
test1 [-s opt_val] parm1 parm2

When using this form, the script requires two operands (parm1 and parm2) and accepts an option which can either be specified as a single command-line argument (-sopt_val) as as two command-line arguments (-s opt_val). In either case, if opt_val contains multiple words, the whitespace between words can be escape or quoted. If parm1 happens to start with a minus sign (-), getopts will accept an operand of -- to indicate end-of-options.

A sample bash (this will also work with any other POSIX conforming shell such as ksh) script for this method is:
Code:
#!/bin/bash
# FIRST EXAMPLE: SYNOPSIS: test1 [-s opt_val] parm1 parm2
# Initialize script variables
IAm=${0##/}     # Last component of this script's pathname
Usage="Usage: %s [-s opt_val] parm1 parm2\n"    # Usage message format string
sopt="None"     # -s option option argument default value

# Parse command line arguments:
# Process options:
while getopts "s:" opt
do      case $opt in
        # Note that with getopts, the -s option and its option argument can be
        # specified as two arguments (-s opt_val) or as one argument
        # (-sopt_val) and the single line of code below will properly handle
        # either case.
        (s)     sopt=$OPTARG;;
        (*)     printf "$Usage" "$IAm" >&2
                exit 1;;
        esac
done
shift $((OPTIND - 1))

# Process operands:
if [ $# -ne 2 ]
then    printf "%s: Expected 2 operands, found %d\n" "$IAm" $#
        printf "$Usage" "$IAm" >&2
        exit 2
fi

# Display values parsed from the command line:
echo "s option option-argument: $sopt"
echo "1st par: $1"
echo "2nd par: $2"

Sample commands and corresponding output for this form follow:
Code:
test1 1 2 3

produces:
Code:
test1: Expected 2 operands, found 3
Usage: test1 [-s opt_val] parm1 parm2

Code:
test1 1st 2nd\ with\ 4\ words

Code:
s option option-argument: None
1st par: 1st
2nd par: 2nd with 4 words

Code:
test1 -s 's opt arg' p1 p2

produces:
Code:
s option option-argument: s opt arg
1st par: p1
2nd par: p2

Code:
test1 -sno_space -- -arg1 arg2

produces:
Code:
s option option-argument: no_space
1st par: -arg1
2nd par: arg2

Code:
test1 -sno_space -arg1 arg2

produces:
Code:
test1: illegal option -- a
Usage: test1 [-s opt_val] parm1 parm2

The 2nd way does not use getopts, but instead just uses $# to determine how many command-line arguments are present. Again it always requires two operands, but this one accepts (but does not require) one more operand and would be described in UNIX-like man pages with the synopsis:
Code:
test2 parm1 parm2 [opt_param]

A sample bash script (that, again, will work with any POSIX conforming shell) for this method is:
Code:
#!/bin/bash
# SECOND EXAMPLE: SYNOPSIS: test2 parm1 parm2 [opt_param]
# Initialize script variables
IAm=${0##/}             # Last component of this script's pathname
Usage="Usage: %s parm1 parm2 [opt_param]\n"     # Usage message format string
opt_parm=${3:-None}     # opt_parm 3rd operand: "None" if not on command line

# Process operands:
if [ $# -lt 2 ] || [ $# -gt 3 ]
then    printf "%s: Expected 2 or 3 operands, found %d\n" "$IAm" $#
        printf "$Usage" "$IAm" >&2
        exit 2
fi

# Display values parsed from the command line:
echo "optional parameter: $opt_parm"
echo "1st par: $1"
echo "2nd par: $2"

Sample commands and corresponding output for this form follow:

Code:
test2 1 2 3 4

produces:
Code:
test2: Expected 2 or 3 operands, found 4
Usage: test2 parm1 parm2 [opt_param]

Code:
test2 '"double quoted string"' "'single quoted string'" optional_operand

produces:
Code:
optional parameter: optional_operand
1st par: "double quoted string"
2nd par: 'single quoted string'

Code:
test2 1st 2nd

produces:
Code:
optional parameter: None
1st par: 1st
2nd par: 2nd

Both of these scripts set the default value for the optional value to "None". It is clear visually for these examples. Depending on how you want to use this optional value, an empty string (or any other string you want) may be more appropriate.

Note that both of these sample scripts redirect all diagnostic messages to stderr (rather than stdout). And, if and only if a diagnostic message is written, the exit status will be non-zero.

Note also that even if a script does not (currently) accept options, it is still a good idea to include comehting like:
Code:
while getopts "" opt
do      case $opt in
        (*)     printf "$Usage" "${0##*/}" >&2
                exit 1;;
        esac
done
shift $((OPTIND - 1))

So a user can always issue the command:
Code:
scriptname "-?"

to get a synopsis for the utility including a list of the currently accepted options, and can use:
Code:
scriptname -- operands

to protect itself in csae the 1st operand might start with a minus sign that should not be interpreted as the start of an option string.

Hope this helps...
This User Gave Thanks to Don Cragun For This Post:
# 5  
Old 06-05-2013
Thank you Don.

Though we already changed all the parameters to options but this thing is very helpful. Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Passing a variable value to an option

Hello, I am new to shell (i.e. linux bash) programming and have the following question: When using this wget command I can download a certain website that needs login information by passing a previously acquired cookie: wget --header='Cookie: SID=ac658ef0876b24ff456' somewebsite.comAs... (5 Replies)
Discussion started by: iggy98
5 Replies

2. Shell Programming and Scripting

Passing parameter through file

Hi , I am passing date parameter through file my shell script testing.sh is #set -x #set -v asd=$1 asd1=$2 echo $asd echo $asd1 Passing parameter as below sh testing.sh `cat file1.txt` Output (2 Replies)
Discussion started by: kaushik02018
2 Replies

3. Shell Programming and Scripting

Passing parameter more than 9

Hi, I've written a script where eleven parameter to be passed from command line which is inserting into an oracle table, it is working but the tenth and 11th parameter are not accepting as given it is referring to 1st parameter. HERE IS THE SCRIPT #!/bin/ksh #set -o echo $*... (4 Replies)
Discussion started by: sankar
4 Replies

4. Shell Programming and Scripting

Passing parameter to script, and split the parameter

i am passing input parameter 'one_two' to the script , the script output should display the result as below one_1two one_2two one_3two if then echo " Usage : <$0> <DATABASE> " exit 0 else for DB in 1 2 3 do DBname=`$DATABASE | awk -F "_" '{print $1_${DB}_$2}` done fi (5 Replies)
Discussion started by: only4satish
5 Replies

5. Shell Programming and Scripting

passing an option as an argument!

Hi Folks I have got to the point where I can specify the arguments but how to pass an option is still mystery to me. Example: temp.csh a b c d set temp1 = $argv set temp2 = $argv set temp3 = $argv echo $temp1 a echo $temp2 b echo $temp3 c d I WANT: temp.csh a b c d -S 1 set temp1... (2 Replies)
Discussion started by: dixits
2 Replies

6. Shell Programming and Scripting

Passing parameter in quotes

Hi, PW='/as sysdba'; export PW in other module I call sqlplus ${PW} (this line I unable to change!) How I can define PW so that sqlplus calls PW in quotes i.e sqlplus '/as sysdba' I tried like this PW="'/as sysdba'"; export PW - no luck Thanks in advance (2 Replies)
Discussion started by: zam
2 Replies

7. UNIX for Dummies Questions & Answers

how does symbolic link execute command with option or parameter

Hello World~:) $ rbash $ cd .. rbash: cd: restricted $ ls -l /bin/rbash lrwxrwxrwx 1 root root 4 2008-11-02 15:56 /bin/rbash -> bash rbash is a symbolic link to bash but why does rbash execute 'bash -r' instead of 'bash' i want to know how symbolic link executes command with option or... (4 Replies)
Discussion started by: lifegeek
4 Replies

8. Shell Programming and Scripting

wrong parameter passing!

Hi all I have a script which will take input as filename and passes it to a java program. It is as follows -------------------------------- FILENAME=$1 echo $FILENAME ${JAVA_HOME}/bin/java -cp DateProvider $FILENAME ------------------------------------------------- when I execute the same... (2 Replies)
Discussion started by: malle
2 Replies

9. Programming

Passing parameter to makefile?

Hi, How to pass parameter to makefile? Please let me know if any one knows and also please put an example of makefile with this feature. thanks, Manju. (3 Replies)
Discussion started by: manju_p
3 Replies

10. Shell Programming and Scripting

parameter passing

Hallo everyone, This is my problem below: /home/cerebrus/pax=>vat class2.sh ksh: vat: not found /home/cerebrus/pax=>cat class2.sh #!/bin/ksh set -x bdf|grep appsdev|awk '{ print $5 }'> class3 dd={cat class3} echo $dd /home/cerebrus/pax=> /home/cerebrus/pax=>./class2.sh + bdf +... (8 Replies)
Discussion started by: kekanap
8 Replies
Login or Register to Ask a Question