[英]Not able to store output of awk command into a variable
我正在嘗試執行以下操作:
#!/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
。 我知道,現在已經解決了這個問題,以避免出現此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.