Home > Software design >  Iterate over a specific command line parameter
Iterate over a specific command line parameter

Time:07-16

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!

CodePudding user response:

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

CodePudding user response:

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


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
  • Related