0

I have this command in bash:

cmd -c -s junk text.txt 

If I change the command to

cmd -c junk -s text.txt

how to I keep track which parameter ($2 or $3) is set to junk?.

I try to use a for loop but I don't know how to find out junk from $@.

1
  • Is cmd a function in bash? What other lines follow from it? Commented Aug 14, 2013 at 8:16

2 Answers 2

1

You need to use getopts inside your script. Something like this should work:

while getopts "c:s:" optionName; do
   case "$optionName" in
   s) arg="$OPTARG"; echo "-s is present with [$arg]";;
   c) arg="$OPTARG"; echo "-c is present with [$arg]";;
   esac
done
Sign up to request clarification or add additional context in comments.

Comments

0

From the example you show it seems that the -s option has a single argument and that is junk in the first example. However the semantics seems to change in the second example and there apparently -c takes a single argument and it is again junk. Also in the second example it seems -s takes text.txt as argument.

In general the arguments in bash commands do not have fixed positions but if an option takes an argument it should directly follow the option parameter(in the first case -s).

As pointed out by anubhava you may use getopts to parse the arguments for your script. Still this will not work for the case where you change the whole semantics like it seems you do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.