LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How can pass both an optional flag and unrelated required parameter to a bash script? (https://www.linuxquestions.org/questions/programming-9/how-can-pass-both-an-optional-flag-and-unrelated-required-parameter-to-a-bash-script-4175479921/)

abefroman 10-07-2013 12:03 PM

How can pass both an optional flag and unrelated required parameter to a bash script?
 
How I can pass both an optional flag and unrelated required parameter to a bash script?

Example, a user can type in:
Code:

./myscript.sh -f myname
or just:
Code:

./myscript.sh myname
I can use getopts to find -f was set, but that sets $1 to "-f" rather than setting it to myname.

I can make $2 myname, but since the -f is optional, that will be $1 sometimes and there won't be a $2.

What is the best way to do this?

TIA

grail 10-07-2013 12:16 PM

Not sure what you have read on getopts (see here or here), but once you have completed this phase of your script you will be at $1
for the first non-switch item ... in your example $1 = myname

abefroman 10-07-2013 12:19 PM

Needed to use shift, thx


All times are GMT -5. The time now is 08:44 AM.