我想打印120个型号列表并同时保留" $"。
我的脚本是:
#!/bin/sh
for i in {1..10};do
declare model="$"model$i
model_list=$(paste $model)
done
echo $model_list
运行后,
paste: $model1: No such file or directory
paste: $model2: No such file or directory
paste: $model3: No such file or directory
paste: $model4: No such file or directory
paste: $model5: No such file or directory
paste: $model6: No such file or directory
paste: $model7: No such file or directory
paste: $model8: No such file or directory
paste: $model9: No such file or directory
paste: $model10: No such file or directory
期望的输出:
$model1 $model2 $model3 $model4 $model5 $model6 $model7 $model8 $model9 $model10
答案 0 :(得分:1)
您必须通过$
(反斜杠美元符号)转义\$
。
例如:
#!/bin/sh
for i in {1..10}; do
declare model="\$"model$i
model_list+=$(paste $model)
done
echo $model_list
您还可以缩短脚本:
#!/bin/sh
for i in {1..10}; do
model_list+=$(paste "\$model${i}")
done
echo $model_list
使用标题为$model1 - $model5
的5个文件进行测试:
File Contents:
$model1 - a b c d e f g
$model2 - 1 2 3 4 5 6 7 8 9 10
$model3 - I J K L M N O P
$model4 - 11 12 13 14 15 16 17 18 19 20
$model5 - q r s t u v w x y z
Output:
a b c d e f g1 2 3 4 5 6 7 8 9 10I J K L M N O P11 12 13 14 15 16 17 18 19 20q r s t u v w x y z
答案 1 :(得分:1)
如果您对输出感兴趣而不是创建数组,则可以使用下面的代码
for i in {1..10};do
echo -n "\$model$i "
done
echo
或
for i in {1..10};do
echo -n '$model'$i' '
done
echo
或
for i in {1..10};do
model_list=$model_list" \$model$i"
done
echo $model_list