2

I want to use for for a set of files.

for file in fileA fileB fileC; do
    COMMAND $file $variable
done

For every $file I want to use specific $variable.
(for example: fileA variableA; fileB variableB)

How can do such association?

  • what version of bash? – iruvar Jun 21 '13 at 23:25
  • GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) – PoGibas Jun 21 '13 at 23:27
  • if [$ID="fileA"] results in command not found here... – Hauke Laging Jun 21 '13 at 23:38
2
declare -A filevars
filevars[fileA]=foo
filevars[fileB]=bar
filevars[fileC]=baz
for file in fileA fileB fileC; do
  echo cmd "$file" "${filevars[$file]}"
done
  • Is it possible to associate multiple variables? varA1 varA2 for fileA, etc? – PoGibas Jun 22 '13 at 0:16
  • @Poe Not directly, bash arrays are one-dimensional. But you can create arrays: arrayindex=0; filevarno[fileA]=$arrayindex; eval filevars_$arrayindex=(varA1 varA2); ((arrayindex++)); ... – Hauke Laging Jun 22 '13 at 1:26
3

Since you are on v4 of bash, associative arrays are an option

declare -A arr
arr=([fileA]=variableA [fileB]=variableB [fileC]=variableC)
for file in "${!arr[@]}"
 do
    command "$file" "${arr[$(basename $file)]}"
done

Note that order of processing may be different from the order within the array definition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.