コマンドプロンプトでif文を実行する

コマンドプロンプトでif文を実行する

Bashでは、次のことができます。

if [ -f /tmp/test.txt ]; then echo "true"; fi

しかし、sudo前に追加すると、もう機能しません。

sudo if [ -f /tmp/test.txt ]; then echo "true"; fi
-bash: syntax error near unexpected token `then'

どのように動作させることができますか?

ベストアンサー1

sudoexecシェルインタプリタを介さずにシェルインタプリタを使用して引数を実行します。したがって、実際のバイナリプログラムに制限され、シェル関数、エイリアス、または組み込み関数(if組み込み関数)は使用できません。-iおよびオプションを-s使用して、それぞれログインまたは非ログインシェルで特定のコマンドを実行できます(または対話的にシェルを実行します。セミコロンをエスケープするか、コマンドを引用する必要があります)。

$ sudo if [ -n x ]; then echo y; fi
-bash: syntax error near unexpected token `then'
$ sudo if [ -n x ]\; then echo y\; fi
sudo: if: command not found
$ sudo -i if [ -n x ]\; then echo y\; fi
y
$ sudo -s 'if [ -n x ]; then echo y; fi'
y

おすすめ記事