0

I have a script with multiple command line parameters and I'd like to use one of them in a for loop. Here is a simplified version:

while getopts s:p: flag
do
    case "${flag}" in
        s) samples=${OPTARG};;
        p) parameter=${OPTARG};;
    esac
done

for sample in $samples
do

    echo "$sample" echo "$parameter"

done

When I run bash script.sh -s Sample1 Sample2 Sample3 -p test I get:

Sample1 echo

But what I would like to get is:

Sample1 test
Sample2 test
Sample3 test

How would I go about this? I only see info for iterating through all the command line parameters using $@ but I don't know how to iterate through a specific command line parameter. Thanks in advance!

1
  • The standard syntax for options that take an argument says that each optio tales one argument. Would it make more sense to make the samples positional arguments (e.g. bash script.sh -p test Sample1 Sample2 Sample3), and use "$@" to iterate over them? Commented Jul 15, 2022 at 23:03

2 Answers 2

1

You need to provide -s multiple times and append the values (or use an array)

#!/bin/bash

while getopts s:p: flag
do
    case "${flag}" in
        s) samples+="${OPTARG} ";;
        p) parameter=${OPTARG};;
        *) exit 1;;
    esac
done

for sample in $samples
do
    echo "$sample" "$parameter"

done

result:

./script.sh -s Sample1 -s Sample2 -s Sample3 -p test
Sample1 test
Sample2 test
Sample3 test
Sign up to request clarification or add additional context in comments.

1 Comment

Solution above can be invoked using script.sh -s{Sample1,Sample2,Sample3} -ptest
1

For the use case when one of the parameters is taking multiple arguments (and assuming you can modify the calling sequence) consider:

Script.sh -p test —- Sample1 Sample2 Sample3

While can be parse using modified version of your code. The advantage is that it’s easier to use with other linux tools. E.g.

 Script.sh -p test Sample*    # if samples are files

Script will be


parameter=defaultvalue    # default for -p, can be empty

while getopts p: flag
do
    case "${flag}" in
        p) parameter=${OPTARG};;
    esac
done
shift $((OPTIND-1))  # remove options for argument list

for sample ; do

    echo "$sample" ; echo "$parameter"

done

2 Comments

This is nice, thank you. How might you add a default parameter to this? I have read that you include p=${1:-default} in your script but that doesn't seem to work and I am not sure where you would put it.
Answer updated for default value

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.