簡體   English   中英

使用awk輸出作為變量進行字符串比較

[英]Use awk output as variable for string comparison

我正在使用簡單的if語句過濾macOS(High Sierra)上ifconfig的輸出以觸發操作,盡管相應的字符串似乎匹配(盡管在用echo測試時),但未觸發該操作。

運行腳本時,如果網絡en1處於活動狀態,則預期的操作是打印“確定”。

我試過了:

  • awk命令中的printf "%s"
  • 使用雙引號(和簡單引號)表示"active"
  • 在比較中保持active的變量
  • en1_status=`...` en1_status=$(...)替換en1_status=`...`

沒有成功。

#!/bin/bash
en1_status=`ifconfig en1 | grep "status: " | awk '{print $2}'`
if [ "$en1_status" = active ]; then
    echo OK
fi

$en1_status似乎與active匹配:

echo $en1_status
active

這通常意味着您的變量中包含不可打印的字符,例如語法突出顯示或DOS換行符。

發生這種情況的一種簡單方法是,如果將grep實例設置為始終插入顏色代碼,例如--color=always而不是默認的(更安全的)-- --color=auto

要跟蹤此情況,請比較以下命令的輸出:

printf '%s' "$en1_status" | xxd
printf '%s' inactive | xxd

您也可以通過讓awk進行搜索來模擬grep的配置:

en1_status=$(ifconfig en1 | awk '/status: / { print $2 }')

您的解決方案在MacOS上有效,如果您在if比較的右側加雙引號(我將本地測試替換inactive ,因為該接口對我而言不是本地活動的):

~/> cat test.sh

#!/bin/bash
en1_status=`ifconfig en1 | grep "status: " | awk '{print $2}'`
if [ "$en1_status" = "inactive" ]; then
    echo OK
fi

當我運行它時:

~/> ./test.sh 
OK

暫無
暫無

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

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