为什么read命令将所有单词读入名字

问题描述:

我的脚本:

#!/bin/bash

IFS=','

read a b c d e f g  <<< $(echo "1,2,3,4,5,6,7") # <- this could be any other commands, I am just making up a dummy command call

echo $a
echo $b
echo $c

我希望它能输出

1
2
3

但是它输出:

1 2 3 4 5 6 7
blank line
blank line

我做错了什么?

您应该像这样使用它:

IFS=, read a b c d e f g  <<< "1,2,3,4,5,6,7"

在与 read 相同的行中使用 IFS ,以避免混乱当前的shell环境.

Use IFS in same line as read to avoid cluttering the current shell environment.

并避免使用命令替换只是捕获单个 echo 命令的输出.

And avoid using command substitution just to capture the output of a single echo command.

如果要在 read 中使用命令的输出,则最好使用 bash 中的"nofollow> 进程替换 :

If you want to use a command's output in read then better use process substitution in bash:

IFS=, read a b c d e f g < <(echo "1,2,3,4,5,6,7")