我正在读取文件的内容并将其存储在2个变量中,然后同时希望使用if语句将其与数组进行比较。代码在下面给出
#!/bin/bash
# Define File
datafile=./regions-with-keys
# Create Nodes File
cat << EOF > $datafile
region1 key1
region2 key2
region3 key3
EOF
# User Input
clear;
echo -ne "PLEASE SELECT REGIONS(s) :\n\033[37;40m[Minimum 1 Region Required]\033[0m"
read -ra a
echo "${a[@]}"
# Reading Regions & Keys
for i in "${a[@]}"
do
while read -r $b $c; do
if [ "${a[@]}" -eq "$b" ]; then
echo "$b" "$c"
fi
done < $datafile
done;
在执行时,它给出了if语句找不到的命令。 代码的目的是如果成功打印,则将用户输入的数组索引与$ datafile中的$ a进行匹配 $ b和$ c
答案 0 :(得分:1)
尝试使用此Shellcheck干净的代码:
#!/bin/bash -p
# Define File
datafile=./regions-with-keys
# Create Nodes File
cat <<EOF >"$datafile"
region1 key1
region2 key2
region3 key3
EOF
# User Input
clear
echo 'PLEASE SELECT REGIONS(s) :'
echo -ne '\e[37;40m[Minimum 1 Region Required]\e[0m'
read -ra input_regions
declare -p input_regions
# Reading Regions & Keys
for input_rgn in "${input_regions[@]}" ; do
while read -r data_rgn key ; do
if [[ $data_rgn == "$input_rgn" ]] ; then
printf '%s %s\n' "$data_rgn" "$key"
fi
done <"$datafile"
done
问题代码中的重大更改是:
declare -p input_regions
以明确的方式打印数组的内容。varname
代替$varname
作为read
的参数。这样可以修复原始代码中的一个严重错误。printf
代替echo
来打印变量值。参见Why is printf better than echo?。[[ ... == ...]]
代替[ ... -eq ... ]
来比较区域名称。[[ ... ]]
比[ ... ]
功能更强大。参见Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?。此外,-eq
用于比较整数,==
(或等效地=
)用于比较字符串。如果您要报告不正确的输入区域,请尝试用以下代码替换“读取区域和键”代码:
for input_rgn in "${input_regions[@]}" ; do
# Find the key corresponding to $input_rgn
key=
while read -r data_rgn data_key ; do
[[ $data_rgn == "$input_rgn" ]] && key=$data_key && break
done <"$datafile"
if [[ -n $key ]] ; then
printf '%s %s\n' "$input_rgn" "$key"
else
printf "error: region '%s' not found\\n" "$input_rgn" >&2
fi
done