ifでエコーは機能しますか?

ifでエコーは機能しますか?

次の機能を考えてください:

function testForBinary {
    someBin=$(command -v binary)
        # Test if binary is installed
        if [[ -n $someBin ]]; then
            installSuccess="Success"
            echo ${installSuccess}
            return
        else
            # This should never be reached
            return 1
        fi
}

(からインポートコンテキスト):

function installAndTestForDialog() {
# dialog allows me to create a pretty installer
# It is a required dependency since XXXXX
# Name Removed as I'm attempting modularization
# of a script from Github that's one huge Script

# See https://unix.stackexchange.com/questions/85249/why-not-use-which-what-to-use-then
    local dialogBin
    local updated=false
    local dialogInstallSuccess

    dialogBin=$(command -v dialog)
    if [[ -z $dialogBin ]]; then
        printf "Installing dialog... "
        if [[ $updated -eq 0 ]]; then
            apt-get update > /dev/null 2>&1
            updated=true
        fi
        # Debian Based OS
        apt-get -y install dialog > /dev/null 2>&1

        # Test if dialog is installed to verify installation
        # above was successful.
        dialogBin=$(command -v dialog)
        if [[ -n $dialogBin ]]; then
            # I cannot get this to echo success
            # if I echo from here
            dialogInstallSuccess="Success"
            # Moving it here doesn't help either  Why??
            echo ${dialogInstallSuccess}
            return
        else
            # This should never be reached
            return 1
        fi
    fi    
}    

ブールで処理しようとしていますが、installSuccess何かが間違っています。上記のように関数を作成した後、

isInstalled=$(testForBinary)
echo "$isInstalled"

isInstalled空の行を返します。command -v binary関数の外部で実行すると、binary結果へのパスは次のようになるため、これが真ではないことがわかります。

出力(コンテキスト):

Function and Variable Output Test
=====================
# These are other tests
# I'm performing, but note
# the blank line, which should
# print Success 
2.9-MODULAR
192.168.1.227
false
false
(blank line)

ベストアンサー1

これはあなたが作ったのと同じくらい複雑で脆弱である必要はありません。

installAndTestForDialog() {
  if command -v dialog &> /dev/null; then
    return 0
  else
    apt-get update &> /dev/null
    apt-get -y install dialog &> /dev/null
  fi
}

ダイアログボックスがすでにインストールされている場合、この関数は0を返します。それ以外の場合はインストールを試み、apt-get installコマンドの終了コードを返します。


@muruがコメントで指摘したように、これは次のように単純化することができます。

if ! command -v dialog; then
    apt-get update
    apt-get install -y dialog
fi > /dev/null 2>&1

または、すでにインストールされていることを確認せずにインストールしてみてください。

{ apt-get update && apt-get -y --no-upgrade install dialog ;} >/dev/null 2>&1

このオプションは、すでにインストールされている場合の--no-upgradeアップグレードを防ぎます。dialog

おすすめ記事