1

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

Cyrus
  • 69,405
  • 13
  • 65
  • 117
manka
  • 13
  • 2
  • To `for dir in fruits/* ` see this question: [Matching folder name using bash](https://stackoverflow.com/q/56821197/3776858) – Cyrus Jun 29 '19 at 23:40

1 Answers1

2

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.

l0b0
  • 48,420
  • 21
  • 118
  • 185
  • Are there no ways to avoid repeating items names? For example, `banana` exists in array and on case condition. I want make it more simple like: `if folder name == array item`. Because I have a lot of folders. Thank you! – manka Jun 29 '19 at 23:47
  • 1
    [Checking whether an array contains an item in Bash](https://stackoverflow.com/q/3685970/96588) is clunky compared to modern languages. For this reason I never recommend Bash for anything more than simple scripts. – l0b0 Jun 29 '19 at 23:59
  • 1
    The puzzle pieces put together: `declare -A A; A=( ["banana"]="yellow" ["apple"]="red" ["watermelon"]="green" ); for dir in fruit/*; do dir=$(basename "$dir"); for key in "${!A[@]}"; do if [[ "$dir" == "$key" ]]; then echo "The color of fruit $key is: ${A[$key]}"; fi; done; done` – Cyrus Jun 30 '19 at 00:01