Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
what version of bash? –  1_CR Jun 21 '13 at 23:25
    
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) –  Pgibas Jun 21 '13 at 23:27
    
if [$ID="fileA"] results in command not found here... –  Hauke Laging Jun 21 '13 at 23:38
add comment

2 Answers

up vote 1 down vote accepted
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
share|improve this answer
    
Is it possible to associate multiple variables? varA1 varA2 for fileA, etc? –  Pgibas 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
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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