簡體   English   中英

如何在bash中使用雙重grep比較(如果/否則)?

[英]How do I use a double grep comparison inside a bash if/else?

我如何在bash if / else中使用double grep比較?

我想跑步:

if [grep  -q $HOSTNAME /etc/hosts] && [grep  -q $IP /etc/hosts]

then

    echo $HOSTNAME and $IP is found into /etc/hosts, test passed OK.

else

    # code if not found
    echo The Hostname $HOSTNAME'/'IP $IP is not found in /etc/hosts, please append it manually. 
    exit 1;
fi

但收到錯誤消息: *too many arguments*

怎么了?

這是您應該執行的操作:

if grep -q "foo" /etc/hosts && grep -q "bar" /etc/hosts; then
   # Both foo and bar exist within /etc/hosts.
else
   # Either foo or bar or both, doesn't exist in /etc/hosts.
fi

錯誤的原因是您無法使用[命令。 就像其他任何命令一樣, [接受您無法通過不將其與參數分開而無法正確提供的參數。

[testPOSIX測試命令。 它可以對文件和字符串進行簡單的測試。 在Bash中,建議您使用功能更強大的[[關鍵字。 [[可以進行模式匹配,使用起來更快捷,更安全(請參閱Bash FAQ 31進一步了解)。

但是,正如您在上面的解決方案中所看到的那樣,您的情況不需要[[[ ,而只是一個if語句來詢問grep退出狀態 *。


退出狀態 *:每個Unix進程都向其父級返回退出狀態代碼。 這是一個無符號的8位值,介於0到255之間(包括0和255)。 除非您專門使用值調用exit ,否則腳本將從上次執行的命令返回退出狀態。 函數還使用return返回值。

嘗試這個,

if grep  -q $HOSTNAME /etc/hosts && grep  -q $IP /etc/hosts
then
    echo "$HOSTNAME and $IP is found into /etc/hosts, test passed OK."
else
    # code if not found
    echo "The Hostname $HOSTNAME'/'IP $IP is not found in /etc/hosts, please append it manually." 
    exit 1;
fi

您的語法失敗: if [grep -q $HOSTNAME /etc/hosts]應該是if [ $(grep -q $HOSTNAME /etc/hosts) ] :在花括號和grep周圍使用空格作為子命令。
這仍然無法正常工作,因為if您希望進行測試而不是測試結果。 我通常使用if [ $(grep -c string file) -gt 0 ]但也可以使用if [ -n "$(grep string file)" ]

我認為您希望主機和ip位於同一行。 在這種情況下,請使用:

if [ -n "$(grep -E "${IP}.*${HOSTNAME}" /etc/hosts)" ]; then
   echo "Found"
fi

# or (using the grep -q)
grep -Eq "${IP}.*${HOSTNAME}" /etc/hosts
if [ $? -eq 0 ]; then

# or (shorter, harder to read for colleages, using the grep -q)
grep -Eq "${IP}.*${HOSTNAME}" /etc/hosts)" && echo "Found"

當您確實要進行兩個測試時,請考慮2個獨立的if語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM