![](/img/trans.png)
[英]Set an environment variable (password) in a way its value is not saved to the bash history
[英]Bash for loop to set a variable, its value, and evaluate it?
如何使用一個for循環定義一個變量,它的價值, 並能夠對其進行評估?
我想不通評估的一部分,但使用for循環定義變量,並將其值似乎工作。 特別,
for i in {1..4}
do
export my${i}var="./path${i}_tofile"
# or
# export my${i}var=./path${i}_tofile
# or
# eval "my${i}var=\"./path${i}_tofile\""
echo $[my${i}var]
done
echo
評估不正確,但是外殼程序確實正確創建了變量和值。
echo $my1var
回報
./path1_tofile
但是我需要使用$i
作為變量名稱的一部分來評估變量。
如果不使用數組,這將變得很復雜:
for i in {1..4}
do
declare my${i}var="./path${i}_tofile"
tmpvar=my${i}var # temporary variabled needed for...
echo "$tmpvar=${!tmpvar}" # bash indirect variable expansion
done
您應該改為使用數組變量:
declare -a myvar
for i in {1..4}
do
myvar[$i]="./path${i}_tofile"
done
更多詳細信息: http : //tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html
只需將您正在使用的回聲替換為:
v=my${i}var
echo ${!v}
然后,腳本:
#!/bin/bash
for i in {1..4}
do
export my${i}var="./path${i}_tofile"
v=my${i}var
echo ${!v}
done
將執行為:
$ ./script
./path1_tofile
./path2_tofile
./path3_tofile
./path4_tofile
但是,老實說,使用間接變量絕非易事。
請考慮使用索引數組(在這種情況下,即使是普通數組也可以使用):
declare -A myvar
for i in {1..4}
do
myvar[i]="./path${i}_tofile"
echo "${myvar[i]}"
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.