2017-06-02 138 views
0

我努力做到以下几点:无法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 

有人能告诉我在脚本中出了什么问题吗?

+0

这与PowerShell无关... – thepip3r

+1

请看看:[我应该怎么做当有人回答我的问题?](http://stackoverflow.com/help/someone-answers) – Cyrus

回答

1

你试图使用将是语法:

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 

小心你的拼写BTW为您发布的代码示例中你有时正确(receiver)拼写接收器和有时会错误(reciever) - 这可能会咬你在某些时候,当你试图使用变量名称,但实际使用不同的名称,而不是翻转ei。我明白,现在问题已经解决,以避免这个问题。

+0

@JonathanLeffler - 感谢您的更正。 –

相关问题