簡體   English   中英

將這兩個IF語句合並為一個?

[英]Combine these two IF statements into one?

將這兩個IF語句組合成一個的任何方法...

if [ -n "$(system_profiler SPPrintersDataType | grep Shared | grep Yes)" ]; then 
    echo 1
fi
if [ -n "$(system_profiler SPPrintersDataType | grep 'System Printer Sharing: Yes')" ]; then 
    echo 1
fi

添加|| 之間的短路評估:

if [ -n ... ] || [ -n ... ]; then ## Something; fi 

|| 被視為邏輯OR(而&&為邏輯AND)。

在您的情況下:

if [ -n "$(system_profiler SPPrintersDataType | grep Shared | grep Yes)" ] || [ -n "$(system_profiler SPPrintersDataType | grep 'System Printer Sharing: Yes')" ]; then 
    echo 1
fi

請注意,如果您使用bash關鍵字[[ ,那么以下內容也有效:

if [[ -n ... || -n ... ]]; then ## Something; fi
[[ -n $(system_profiler SPPrintersDataType | grep Shared | grep Yes)$(system_profiler SPPrintersDataType | grep 'System Printer Sharing: Yes') ]] && echo 1

注意:

  • 如果其中一個字符串為非空或另一個為非空,則要回顯1。 在這種情況下,對字符串進行分類並查看結果會更簡單:如果結果為非空,則至少一個輸入字符串必須為非空。

  • 在這種情況下,無需使用if語句(盡管不是禁止的)。

  • 如果使用[[ ... ]]測試字符串,則無需在-s加上引號。

  • 當您為Shared使用 grep時,是否應允許在行中Shared字樣之前出現Yes字樣? 如果沒有,那么寫grep 'Shared.*Yes會更簡單。

  • 由於您對grep命令的實際輸出不感興趣,而僅對它匹配的事實感興趣,因此類似的方法也可以:

     {system_profiler SPPrintersDataType|grep -q 'Shared.*Yes} || {system_profiler SPPrintersDataType|grep -Fq 'System Printer Sharing: Yes'} && echo 1 
  • 最后,假設system_profiler命令在兩個調用中產生相同的輸出,則代碼可以簡化為:

     {system_profiler SPPrintersDataType|grep -Eq 'Shared.*Yes|System Printer Sharing: Yes'} && echo 1 

基本上這樣說的: 如果system_profiler中有一行包含Shared ... Yes或一行包含System Printer Sharing是,則echo 1 您需要-E才能獲得| 以正則表達式模式工作。

誠然,所有這些建議意味着,如果條件滿足,您只會得到一個1 ,而如果您同時滿足兩個條件,則在原始解決方案中,您將得到兩個1 因此,我的解決方案並不完全等同於您的解決方案。 但是,由於您明確表示要合並這些案例,因此我認為這是可以接受的。

我不知道您的system_profiler的輸出看起來如何,因此在這里進行一些猜測。 如果“ SharedYes是”在一行中始終保持相同順序,則可以將它們與

grep 'Shared.*Yes'

您可以一次通過兩個步驟來對兩個表達式進行grep

grep 'Shared.*Yes\|System Printer Sharing: Yes'

然后,您可以將命令編寫為

system_profiler SPPrintersDataType \
  | grep -q 'Shared.*Yes\|System Printer Sharing: Yes' \
    && echo 1

注意我們使用grep -q來抑制輸出,因為我們只對返回碼感興趣。

還要注意,如果兩個字符串都存在,我們只會輸出一個1我猜這就是您想要的,但是我提到它是因為它與您的腳本有所不同。

暫無
暫無

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

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