LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 10-07-2013, 12:03 PM   #1
abefroman
Senior Member
 
Registered: Feb 2004
Location: lost+found
Distribution: CentOS
Posts: 1,430

Rep: Reputation: 55
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
 
Old 10-07-2013, 12:16 PM   #2
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 9,999

Rep: Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190Reputation: 3190
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
 
1 members found this post helpful.
Old 10-07-2013, 12:19 PM   #3
abefroman
Senior Member
 
Registered: Feb 2004
Location: lost+found
Distribution: CentOS
Posts: 1,430

Original Poster
Rep: Reputation: 55
Needed to use shift, thx
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
how to pass command-line parameter to shell script? Kropotkin Linux - Newbie 12 07-25-2011 09:24 AM
bash script - parsing optional parameters yitzle Programming 5 02-17-2008 11:16 AM
how to pass in a parameter to a perl script new_2_unix Linux - Newbie 2 12-09-2007 12:48 AM
bash: pass a parameter to xview nimra Programming 2 06-28-2004 09:18 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:39 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration