我想从bash中的数据文件中读取以下变量。
#/tmp/input.dat
$machie=1234-567*890ABC
$action=REPLACE
$location=test_location
感谢您的帮助。
泰斯
答案 0 :(得分:4)
#!/usr/bin/env bash
case $BASH_VERSION in
''|[0-3].*) echo "ERROR: Bash 4.0 or newer is required" >&2; exit 1;;
esac
# read input filename from command line, default to "/tmp/input.dat"
input_file=${1:-/tmp/input.dat}
declare -A vars=()
while IFS= read -r line; do
[[ $line = "#"* ]] && continue # Skip comments in input
[[ $line = *=* ]] || continue # Skip lines not containing an "="
line=${line#'$'} # strip leading "$"
key=${line%%=*} # remove everything after first "=" to get key
value=${line#*=} # remove everything before first "=" to get value
vars[$key]=$value # add key/value pair to associative array
done <"$input_file"
# print the variables we read for debugging purposes
declare -p vars >&2
echo "Operation is ${vars[action]}; location is ${vars[location]}" >&2
请参阅:
[1] - 请注意,如果您不将使用关联数组,如本答案所示,出于安全考虑,最好使用前缀命名空间:printf -v "var_$key" %s "$value"
- 生成您将取消引用为$var_action
或$var_location
的变量名称 - 比printf -v "$key" %s "$value"
更安全,因为前者确保您的数据文件可以&# 39; t覆盖安全性至关重要的环境变量,例如PATH
或LD_PRELOAD
,通过导致此类尝试无害地设置$var_PATH
或$var_LD_PRELOAD
。 < / p>