gpt4 book ai didi

bash - 从 bash 脚本到无限循环中的 bash 脚本

转载 作者:行者123 更新时间:2023-11-29 09:31:51 26 4
gpt4 key购买 nike

我的脚本的“只运行一次”版本的一个非常简单的示例:

./myscript.sh var1 "var2 with spaces" var3
#!/bin/bash
echo $1 #output: var1
echo $2 #output: var2 with spaces
echo $3 #output: var3

按预期工作!现在我尝试只启动脚本并在循环中输入变量,因为稍后我想一次将多个数据集复制到 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

似乎 read 在空格处拆分输入,将所有剩余的内容放在最后一个 var 中,对吗?有没有更好的可能性在循环中添加变量?或者如何让我的行为像我在脚本后面添加变量一样?

那种在循环中执行一个脚本同时将不同的变量复制到 shell 的循环的英文单词是什么?如果我不知道它叫什么,就无法通过谷歌搜索样本...

最佳答案

这会读取 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 手册页以获取 set .

--
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 ‘-’.

关于bash - 从 bash 脚本到无限循环中的 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com