簡體   English   中英

if 語句,調用 function 並將值與變量進行比較

[英]if statement, that calls a function and compares values to variables

我使用 i3 並想使用調用 pactl 的音量鍵來控制我的接收器的音量。 由於 pactl 不支持最大音量參數,但建議與 pipwire 一起使用,腳本應該獲取當前音量並進行比較,如果下一個 volume_increment 步驟會導致比某個 max_volume 更高的值。 我的困惑現在與 if 語句有關,結合計算 volume_increment 和 max_volume 之間的差異,並將其與 current_volume function 的結果進行比較。因此音量將提高,直到某個值,其中增量將導致音量高於最大值

#!/bin/bash

volume_increment=$1
max_volume=$2

function get_volume() {
pactl get-sink-volume @DEFAULT_SINK@ | head -n1 | cut -d/ -f2 | tr -d ' %'
}
 
if (( get_volume >= $max_volume - $volume_increment )) ; then
    pactl set-sink-volume @DEFAULT_SINK@ +$volume_increment%
else
    pactl set-sink-volume @DEFAULT_SINK@ $max_volume%
fi

我在 google 上搜索了很多,並在 if 語句中嘗試了幾種括號變體。 我已經設法讓它在某個中間步驟工作。 但是后來我讀到 (()) 括號對於 POSIX shell 並不通用。

現在我很困惑,無法在腦海中區分這些不同的方面。 有人會如此友好地解釋在語句中調用 function 的邏輯並將其與變量的差異進行比較嗎? 最好用於通用 POSIX 用法,螺母 bash 特定。

請注意,在算術上下文中,變量是隱式擴展的。 因此, ((var))自動使用$var

在你的聲明中

(( get_volume >= $max_volume - $volume_increment ))

不需要 $ - 您同樣可以編寫max_volume - volume_increment ,但您指的是變量get_volume並且從未設置它。 未設置的變量被視為零,因此get_volume始終為 0。假設您可以從 function current_volume計算此值,您可以執行

get_volume=$(current_volume)

或者直接在算術表達式中運行這個 function,即

(( $(current_volume) >= $max_volume - $volume_increment ))

當然,所有這些都要求您在腳本中將自己限制為 integer 算術。

暫無
暫無

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

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