Search code examples
bashshellglob

Matching directory names and taking action with array


Can you help me?

I want create a dynamic folder match, and if the folder name match an item in array, then an output will be triggered according the folder name. Here is an example.

#!/bin/bash
A=("banana"=>"yellow", "apple"=>"red", "watermelon"=>"green")
for dir in fruits/* 
do 
    if [ "$dir" = "{banana, apple or watermelon}" ]; then 
        echo "The color of the fruit is: {fruit-color}"
    fi
done

But I have no idea about how can I start, I only did this simple code above to you understand. Can you help me?

Thank you very much


Solution

  • Associative arrays are created this way:

    declare -A fruit
    fruit=( ["banana"]="yellow" ["apple"]="red" ["watermelon"]="green" )
    

    Your conditional can be implemented as a case statement:

    case "$dir" in
        banana|apple|watermelon)
            echo "The color of the fruit is: ${fruit[$dir]}"
            ;;
        *)
            break
    esac
    

    Matching the keys is a bit clunky but can be done:

    for key in "${!fruit[@]}"
    do
        if [[ "$dir" = "$key" ]]
        then
            echo "The color of the fruit is: ${fruit[$key]}"
        fi
    done
    

    Running the resulting script through shellcheck is a good idea, and Greg's Wiki is a great place to learn Bash.