如何檢查busybox是否有指令?

如何檢查busybox是否有指令?

就我而言,我想看看 busybox 是否內建了「md5sum」。

我目前正在這樣做:

$ echo | busybox md5sum &>/dev/null && echo yes || echo no

我無法找到任何關於 busybox 中是否內建了任何內容來以程式設計方式查詢可用功能的資訊。

是的,我可以透過不帶參數來運行它來列出可用的小程序,但嘗試 grep 輸出會很容易出錯,並且不能保證 grep 是否可用。

答案1

謝謝你的推動,米卡。它讓我的創造力源源不絕。

更新:

在 Bash 3/4 上測試,所有內建函數,無依賴性:

可移植性:僅 100% 相容於 Bash 3 和 Bash 4

function _busybox_has() {
   builtin command -v busybox >/dev/null ||
      return 1
   
   # Sanitize searches for '[' and '[['
   a=$1
   a=${a//[/\\[}
   
   [[ $(busybox) =~ [[:space:]]($a)([,]|$) ]] ||
     return 1
}

無 bashisms,在 Dash 上測試:

可移植性:可在所有具有 sed/egrep 的 sh 上移植

_busybox_has() {
   busybox >/dev/null 2>&1 ||
      return 1
   
   # Sanitize searches for '[' and '[['
   a=$(echo "$1" | sed 's/[[]/\\[/g')
   
   busybox | egrep -oq "[[:space:]]($a)([,]|$)" ||
      return 1
}

沒有 bashisms,grep -e 取代 egrep(更便攜),在 Dash 上測試:

可移植性:可透過 sed/grep -e 在所有 sh 上移植

_busybox_has() {
   busybox >/dev/null 2>&1 ||
      return 1
   
   # Sanitize searches for '[' and '[['
   a=$(echo "$1" | sed 's/[[]/\\[/g')
   
   busybox | grep -oqe "[[:space:]]\($a\)\([,]\|\$\)" ||
      return 1
}

去測試:

_busybox_has md5sum && echo yes || echo no

答案2

如果我# busybox不帶參數輸入,我會得到一個可能的已配置命令的清單。

根據您的環境,您可以解析該字串。提到了 Grep,但缺少該選項,我將透過我的環境中的字串解析工具來處理它:

重擊:

options=$('busybox');

if [[ $options == *command* ]]
then
  echo "It's there!";
fi

如果您使用另一種語言,通常會有合適的語言。

答案3

busybox --list | busybox grep -qF md5sum && echo yes || echo no

(在 Debian 12 中使用 Busybox v1.35.0 進行測試。)

實作上述解決方案的 shell 函數:

_busybox_has () { busybox --list | busybox grep -qxF "$1"; }

用法:

_busybox_has md5sum && echo yes || echo no
_busybox_has kitchensink && echo yes || echo no

無法保證是否grep可用

grep如此有用,如果沒有它,那就太奇怪了。為了以防萬一,以下 shell 函數_busybox_has僅使用busybox --listPOSIX 的 和 功能sh(而不是[)來實現:

_busybox_has () {
busybox --list | ( while IFS= read -r line; do
   case "$line" in
      "$1") return 0
         ;;
   esac
done
return 1 )
}

相關內容