コマンドからの出力が空でない場合、ls | grep something
いくつかのステートメントを実行したい if/then ステートメントを実行しようとしています。使用すべき構文がわかりません。私はこれのいくつかのバリエーションを試しました:
if [[ `ls | grep log ` ]]; then echo "there are files of type log";
コマンドからの出力が空でない場合、ls | grep something
いくつかのステートメントを実行したい if/then ステートメントを実行しようとしています。使用すべき構文がわかりません。私はこれのいくつかのバリエーションを試しました:
if [[ `ls | grep log ` ]]; then echo "there are files of type log";
まあ、それは近いですが、で終了する必要がありif
ますfi
。
また、if
コマンドを実行し、コマンドが成功した場合 (ステータス コード 0 で終了) に条件付きコードを実行します。grep
これは、少なくとも 1 つの一致が見つかった場合にのみ実行されます。したがって、出力を確認する必要はありません。
if ls | grep -q log; then echo "there are files of type log"; fi
grep
("quiet") オプションをサポートしていない古いバージョンまたは非 GNU バージョンのシステムを使用している場合は-q
、出力を にリダイレクトすることで同じ結果を得ることができます/dev/null
。
if ls | grep log >/dev/null; then echo "there are files of type log"; fi
ただしls
、指定されたファイルが見つからない場合もゼロ以外を返すためgrep
、D.Shawley の回答のように、まったくなくても同じことができます。
if ls *log* >&/dev/null; then echo "there are files of type log"; fi
ls
少し冗長ですが、シェルのみを使用して、 を使用せずに実行することもできます。
for f in *log*; do
# even if there are no matching files, the body of this loop will run once
# with $f set to the literal string "*log*", so make sure there's really
# a file there:
if [ -e "$f" ]; then
echo "there are files of type log"
break
fi
done
特にbashを使用している限り、nullglob
オプションを設定してそれをいくらか簡素化できます:
shopt -s nullglob
for f in *log*; do
echo "There are files of type log"
break
done
またはなしif; then; fi
:
ls | grep -q log && echo 'there are files of type log'
あるいは:
ls *log* &>/dev/null && echo 'there are files of type log'
ビルトインはif
シェル コマンドを実行し、コマンドの戻り値に基づいてブロックを選択します。 ls
要求されたファイルが見つからない場合は個別のステータス コードを返すため、grep
パーツは必要ありません。この[[
ユーティリティは、実際には算術演算を実行する bash IIRC の組み込みコマンドです。私は Bourne シェルの構文から外れることはめったにないので、その部分で間違っている可能性があります。
とにかく、これらすべてをまとめると、次のコマンドになります。
if ls *log* > /dev/null 2>&1
then
echo "there are files of type log"
fi