#!/bin/bash
ARG_ARRAY=(num1 num2 num3 num4 num5 num6 num7 num8 num9 num10)
dir=$(find . -type f)
i=0
for f in ${dir[@]};do
printf "$((++i)) $f "
done
printf "\nPlease select the files:\n"
echo "Using the numbers like: 1 2 4 5 "
read ${ARG_ARRAY[@]}
echo $num1
echo $num2
echo $num3
echo $num4
echo $num5
echo $num6
echo $num7
echo $num8
echo $num9
echo $num10
for f in ${ARG_ARRAY[@]}
do
var=$f
echo ${$var}
done
上面的代码打算显示所有文件。让usr选择它们,然后打印用户选择的文件名。但我发现这个序列可以成功打印
echo $num1
echo $num2
echo $num3
echo $num4
echo $num5
echo $num6
echo $num7
echo $num8
echo $num9
echo $num10
虽然这会得到错误
for f in ${ARG_ARRAY[@]}
do
var=$f
echo ${$var}
done
./test.sh: line 30: num1: command not found
./test.sh: line 30: num2: command not found
./test.sh: line 30: num3: command not found
./test.sh: line 30: num4: command not found
./test.sh: line 30: num5: command not found
./test.sh: line 30: num6: command not found
./test.sh: line 30: num7: command not found
./test.sh: line 30: num8: command not found
./test.sh: line 30: num9: command not found
./test.sh: line 30: num10: command not found
有人可以帮我解决这个问题吗?为什么第二种方式失败了?
答案 0 :(得分:3)
您可以将eval
用于此目的,例如:
for f in ${ARG_ARRAY[@]}
do
var=$f
eval echo \$$var
done