linux - 无法将 awk 命令的输出存储到变量中

标签 linux bash shell awk

我正在尝试执行以下操作:

#!/bin/bash

echo "Enter Receiver HostNames (comma separated hostname list of receivers):"
read receiverIpList

receiver1=`$receiverIpList|awk -F, '{print $1}'`

echo $receiver1

当我运行脚本时出现以下错误。

./test1.sh
Enter Receiver IP Addresses (comma separated IP list of receivers):
linux1,linux2
./test1.sh: line 6: linux1,linux2: command not found

谁能告诉我脚本中有什么问题吗??

最佳答案

您尝试使用的语法是:

receiver1=`echo "$receiverIpList"|awk -F, '{print $1}'`

但是你的做法是错误的。只需将输入直接读入 bash 数组并使用它:

$ cat tst.sh
echo "Enter Receiver HostNames (comma separated hostname list of receivers):"
IFS=, read -r -a receiverIpList
for i in "${!receiverIpList[@]}"; do
  printf '%s\t%s\n' "$i" "${receiverIpList[$i]}"
done

$ ./tst.sh
Enter Receiver HostNames (comma separated hostname list of receivers):
linux1,linux2
0   linux1
1   linux2

即使出于某种原因你不想这样做,你仍然不应该使用 awk,只需使用 bash 替换或类似的,例如:

$ foo='linux1,linux2'; bar="${foo%%,*}"; echo "$bar"
linux1

请注意您的拼写,顺便说一句,在您发布的代码示例中,您有时会正确拼写接收器 (receiver),有时会错误地拼写 (reciever) - 这可能会很麻烦当您尝试使用变量名但实际上由于翻转 ei 而使用不同的变量名时,您会遇到这种情况。我明白了,这个问题现在已经解决以避免这个问题。

关于linux - 无法将 awk 命令的输出存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332608/

相关文章:

c - 如何在客户端服务器模型中通过套接字发送和接收换行符?

php - 使用 crontab 运行 bash 脚本时遇到问题

python - 在docker容器内调用命令

bash - 如何在 linux [bash shell] 中传递 ' [单引号字符] 作为参数?

arrays - 如何将数组传递给函数并且对数组的更新反射(reflect)在函数之外

shell - 如何在postgresql中使用for循环创建多个表

linux - PAM 模块是否可以防止用户多次登录?

linux - 在 Linux 中使用 head 和 tail 返回文件的第 n 项

perl - 管道元素或将它们指定为 Perl 单行代码中的参数有什么区别?

bash - 使用 awk 从标准输入或文件中读取