bashから条件付きで出力をstdoutまたは/dev/nullにリダイレクトできますか?

bashから条件付きで出力をstdoutまたは/dev/nullにリダイレクトできますか?

例:

私はこのスクリプトをテスト実行として受け入れて実行するのではなく、コマンドを印刷する--simulateスクリプトを作成しています。正常に実行されている場合(つまり、使用されていない場合--simulate)、実行中のコマンドはコンソールに多くの出力を生成します。

現在の

私は現在これと似た(少し単純化された)作業をしており、Windowsゲームに関連する排他的なアーカイブ形式の複数の圧縮ファイルを介してループを実行しています。

# flag variable
mode='';
if [[ "--simulate" == "$1" ]]; then
    mode="echo";
fi

# command is a long wine command that takes a mess of arguments
# and generates a LOT of output
${mode} command

どこに付いてるの?

${mode} commandコンソールの騒音を避けるためにtoを変更しようと思ったとき、これが${mode} command 2>&1 >/dev/nulltoから出力を送信する効果もあることに気づきました。echo--simulate/dev/null

1つのオプションはIFブロックを使用しtestてステートメントの複数のコピーを保持することですが、より良い方法があるかどうか疑問に思います。

次のようなことをする方法があると思いましたが、Google/ここで見つけることができないので、私は知りません。

# flag variable
mode='';
redirectOutputTo='/dev/null';
if [[ "--simulate" == "$1" ]]; then
    mode="echo";
    redirectOutputTo="stdout";
fi

# If this is run as is, it will just create a file named 'stdout' in the script folder
# bc I assume that is not the real name. Ditto for using '&1'; just creates a file.
${mode} command 2>&1 >${redirectOutputTo}

バッシュ/OSバージョン

違いがある場合、私のシステムが実行される環境は次のとおりです(Mint 19.3 x64)。

$ bash --version|head -1
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

$ uname -vo
#56~18.04.1-Ubuntu SMP Wed Jun 24 16:17:03 UTC 2020 GNU/Linux

ベストアンサー1

シェル関数を使用してください。

runmaybe () {
  if [[ $mode == "--simulate" ]]
  then echo $@
  else $@ 2>&1 > /dev/null
  fi
}

概念の証明は次のとおりです。

#!/bin/bash

filethatwillsavestderr="/tmp/foo"
filethatwillsavestdout="/tmp/bar"

mode="--simulate" #switch this to another mode to see the effect

runmaybe () {
  if [[ $mode == "--simulate" ]]
  then echo "I should run '$@' but i'm not really doing it"
  else $@ > $filethatwillsavestdout 2> $filethatwillsavestderr
  fi
}

runmaybe ls

おすすめ記事