Execute specific command based on an array variable

Hi there,

I'm working with a short pipeline which will take as input three different parameters. The first one is the default command with no parameter, the second command introduces the option --intra, whereas the third uses both --intra and -C.

Now, I thought about building a three-element array as such:

PARAM=("foo" "--intra" "-C")

to iterate over the command three times without having to rewrite the code block over and over again. I've attempted the more simple:

for $STR in ${PARAM[@]}; do
    echo ${STR}   
done

but also with conditional statements as follows:

for STR in ${PARAM[@]}; do
    if [[ ${STR} -eq ${PARAM[0]} ]]; then
        echo "standard"
    elif [[ ${STR} -ne ${PARAM[0]} ]] && [[ ${STR} -ne ${PARAM[2]} ]]; then
        echo "second case"
    else
        echo "last case"
    fi
done

The problem with the first one is that I have no control over the case when I want to use both --intra and -C (third case), the second attempt – and many others on that line I've made – never displays the last case scenario.

Does someone have any suggestion on how to do this, I'm open to possible better implementations. Let me know, thanks in advance!

P. S. the first element of the array can also be an empty string like "" if that helps

One issue in your code @overcraft is due to your incorrect handling of string comparisons and the conditional logic.

In Bash, you should use == for string comparison instead of -eq and -ne, which are for numeric comparisons.

Also, you should use double quotes around variables ("$STR") to handle cases where elements might be empty strings (for example, "").

For example, consider this:

#!/bin/bash

# Define the parameter array
PARAM=("foo" "--intra" "-C")

# Iterate over each element in the PARAM array
for STR in "${PARAM[@]}"; do
    if [[ "$STR" == "${PARAM[0]}" ]]; then
        echo "standard"
    elif [[ "$STR" == "${PARAM[1]}" ]]; then
        echo "second case"
    elif [[ "$STR" == "${PARAM[2]}" ]]; then
        echo "last case"
    fi
done
2 Likes

@Neo much appreciated! I now understand the meaning of the "$STR" which I've seen often being used, thanks for the explanation.

About the -eq and -ne, it's on my side. I must have misinterpreted the information here and though they were interchangeable with ==, != etc. Although at a second look, it is explicitly said the former are arithmetic and the latter for string comparison.

Thanks again!

It can make sense to loop over the indexes:

for IND in ${!PARAM[@]}; do
    STR=${PARAM[$IND]}
    if [[ $IND -eq 0 ]]; then
        echo "standard $STR"
    elif [[ $IND -eq 1 ]]; then
        echo "second case $STR"
    else
        echo "last case $STR"
    fi
done

echo ${!PARAM[@]}
gives
0 1 2

1 Like

@MadeInGermany interesting! Really thankful you provided another way to do so.