LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   get n-variable parameters in bash (https://www.linuxquestions.org/questions/linux-newbie-8/get-n-variable-parameters-in-bash-870008/)

xeon123 03-21-2011 11:08 AM

get n-variable parameters in bash
 
Hi,

I've a script that it's invoked with n-variable parameters. Here's an examples:

Code:

./myprogram.sh inputdir FIELD1 FIELD2 ... FIELDN outputfile
In the script I would like to get the FIELD names that were passed.

How can I do that in bash?

colucix 03-21-2011 11:17 AM

You can try the shift statement inside a loop to cycle through all the positional parameters (arguments) independently from their number, e.g.
Code:

until [[ -z $1 ]]
do
  echo $1
  shift
done

the loop is executed until $1 is null. Please, see the Bash Reference Manual for more details.

xeon123 03-21-2011 11:20 AM

I've found it.
The command getopt worked for me.

SaintDanBert 03-21-2011 11:25 AM

Given a command line:
Code:

prompt$ verb  option1  option2  ...  optionN
where is token is a group of characters separated by whitespace(blanks, tabs, etc)

You access them within your bash script as:
  • $0 -- the name of the "verb" (see more below)
  • $1 $2 ... $9 -- each option in order from left to right
  • $* -- all of the options as a single value
You may learn more at a terminal with
Code:

prompt$ man bash
and read about "Positional Parameters". NOTE -- 'man' launches the 'less' page reader.
Within less, type "/Positional" to search for that string.

If you have more than nine space-separated options, there is a built-in command, 'shift' to drag more options into place. Again 'man bash' is your friend.

The value of $0 is actually the full file path and name to the running script. So if you are running a script named "framis" that is stored in "/usr/local/bin", the verb will appear as "/usr/local/bin/framis".

Bonne chance,
~~~ 0;-Dan

grail 03-21-2011 08:26 PM

Quote:

Originally Posted by SaintDanBert
If you have more than nine space-separated options, there is a built-in command, 'shift' to drag more options into place.

Actually this is not required, but of course still works. You can however simply use the following for greater than 9:
Code:

echo ${10}


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