2016-04-28 54 views
0

我有一些文件,如:如何使文件從FILE {1-3}變量值for循環?

FILE1="apple.txt" 
FILE2="grapes.txt" 
FILE3="strawberry.txt" 

我怎麼能在bash使這些文件?

我嘗試這樣做,但我得到了一個錯誤......

for f in {1..3} 
do 
    echo hello > $(FILE$f) 
done 

錯誤:

./make_files.sh: line 48: FILE1: command not found 
./make_files.sh: line 48: $(FILE$f): ambiguous redirect 

我需要它們含有你好3 txts,蘋果,葡萄和草莓。

回答

2

我猜你想要做的是,這三個名字創建的文件: apple.txt,grapes.txt和strawberry.txt

,所以你應該做的:

for f in {1..3} 
do 
    TMP="FILE$f" 
    echo hello > "${!TMP}" 
done 
1

IIUC,你想這樣:

for f in {1..3} 
do 
    echo hello > FILE"$f" 
done 

編輯:

基於另一個回答您的評論我覺得你真的想這樣:

for f in {1..3} 
do 
    echo hello > $(< FILE"$f") 
done 

例子:

$ ls 
FILE1 FILE2 FILE3 
$ cat FILE1 FILE2 FILE3 
apple.txt 
grapes.txt 
strawberry.txt 
$ for f in {1..3} 
> do 
>  echo hello > $(< FILE"$f") 
> done 
$ cat apple.txt grapes.txt strawberry.txt 
hello 
hello 
hello 
1

還是做這一切在一次:

for f in FILE{1..3}; do 
    echo hello >"${!f}" 
done 

主要錯誤在你的代碼是$( ... ),這是命令替換:它試圖運行名稱FILE1FILE2等。 作爲命令,以便使用這些命令的輸出作爲要寫入的文件的名稱。

你想要做的是使用那些作爲參數名稱。要間接檢索其名稱存儲在另一個參數中的參數值,請使用!,如${!f}中所示。

但大多數的時候,你在做這樣的事情,你最好使用一個數組:

FILES=("apple.txt" "grapes.txt" "strawberry.txt") 
for f in "${FILES[@]}"; do 
    echo hello >"$f" 
done 
+0

它寫出你好,到FILE1,FILE2,FILE3。但是我需要向apple.txt寫出你好,等等。 – tmsblgh