我正在尝试执行以下操作:
#!/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/