为什么这个 bash 脚本不分割字符串?
我正在尝试用两个由空格分隔的单词分割一个字符串,但是这个片段对我不起作用:
$ cat > test.sh
#/bin/bash
NP="3800 480"
IFS=" "
echo $NP
echo $NP | read VAR1 VAR2
echo "Var1 : $VAR1"
echo "Var2 : $VAR2"
exit 0
调用它会给我:
$ chmod 755 ./test.sh && ./test.sh
3800 480
Var1 :
Var2 :
我希望看到的地方:
3800 480
Var1 : 3800
Var2 : 480
如何分割像这样的简单字符串在 bash 脚本中?
编辑:(我使用的答案) 感谢 jw013 提供的链接,我能够想出这个适用于 bash 2.04 的解决方案:
$ cat > test.sh
#!/bin/bash
NP="3800 480"
read VAR1 VAR2 << EOF
$NP
EOF
echo $VAR2 $VAR1
$./test.sh
480 3800
I'm trying to split a string with two words delimited by spaces, and this snippet isn't working for me:
$ cat > test.sh
#/bin/bash
NP="3800 480"
IFS=" "
echo $NP
echo $NP | read VAR1 VAR2
echo "Var1 : $VAR1"
echo "Var2 : $VAR2"
exit 0
And invoking it gives me:
$ chmod 755 ./test.sh && ./test.sh
3800 480
Var1 :
Var2 :
Where I was hoping to see:
3800 480
Var1 : 3800
Var2 : 480
How can a split a simple string like this in a bash script?
EDIT: (Answer I used)
Thanks to the link provided by jw013, I was able to come up with this solution which worked for bash 2.04:
$ cat > test.sh
#!/bin/bash
NP="3800 480"
read VAR1 VAR2 << EOF
$NP
EOF
echo $VAR2 $VAR1
$./test.sh
480 3800
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是管道涉及一个分支,因此您需要确保脚本的其余部分在执行读取操作的 shell 中执行。
只需添加
( ... )
如下:The problem is that the pipeline involves a fork, so you will want to make sure the rest of your script executes in the shell that does the read.
Just add
( ... )
as follows:使用 bash,您可以使用
<<<
(“此处字符串”,从字符串重定向输入):With bash, you can use
<<<
(a "here string", redirect input from a string):也会起作用
would also work
请查看 BashFAQ 024,了解有关使用
read
的更多信息,以便您稍后可以访问变量。我最喜欢的解决方案(比仅 bash 的解决方案更便携)是这里的文档之一:
Take a look at BashFAQ 024 for more about using
read
so that you can access the variables later.My favorite solution (being more portable than the bash-only ones) is the here doc one: