我的脚本“只运行一次”版本的一个非常简单的示例:
./myscript.sh var1 "var2 with spaces" var3
#!/bin/bash
echo $1 #output: var1
echo $2 #output: var2 with spaces
echo $3 #output: var3按计划工作!现在,我尝试启动脚本并在循环中输入vars,因为稍后我希望将多个数据集一次复制到shell中。
./myscript.sh
#!/bin/bash
while true; do
read var1 var2 var3
#input: var1 "var2 with spaces" var3
echo $var1 #output: var1
echo $var2 #output: "var2
echo $var3 #output: with spaces" var3
done它似乎在空格处拆分了输入,把所有剩下的都放在最后一个变量中,对吗?在循环中添加vars是否有更好的可能性?或者我如何被读到就像我在脚本后面添加了vars一样?
在将不同的vars复制到shell时,在循环中执行一个脚本的这种循环的英文单词是什么?如果我不知道它叫什么.
发布于 2015-01-26 14:44:01
它读取STDIN并将这些行解析为带有shell引用的参数:
# Clean input of potentially dangerous characters. If your valid input
# is restrictive, this could instead strip everything that is invalid
# s/[^a-z0-9" ]//gi
sed -ue 's/[][(){}`;$]//g' | \
while read input; do
if [ "x$input" = "x" ]; then exit; fi
eval "set -- $input"
# check argument count
if [ $(( $# % 3 )) -ne 0 ]; then
echo "Please enter 3 values at a time"
continue;
fi
echo $1
echo $2
echo $3
done所有的魔法都是set -- $input做的。有关设置,请参见Bash手册页面。
--
If no arguments follow this option, then the positional parameters are
unset. Otherwise, the positional parameters are set to the arguments,
even if some of them begin with a ‘-’.https://stackoverflow.com/questions/28151987
复制相似问题