![bash でプレフィックスを持つ 1 つ以上のファイルが存在するかどうかをテストするにはどうすればよいでしょうか? 例: [[-f foo*]]](https://rvso.com/image/178564/bash%20%E3%81%A7%E3%83%97%E3%83%AC%E3%83%95%E3%82%A3%E3%83%83%E3%82%AF%E3%82%B9%E3%82%92%E6%8C%81%E3%81%A4%201%20%E3%81%A4%E4%BB%A5%E4%B8%8A%E3%81%AE%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%8C%E5%AD%98%E5%9C%A8%E3%81%99%E3%82%8B%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E3%83%86%E3%82%B9%E3%83%88%E3%81%99%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%82%88%E3%81%84%E3%81%A7%E3%81%97%E3%82%87%E3%81%86%E3%81%8B%3F%20%E4%BE%8B%3A%20%5B%5B-f%20foo*%5D%5D.png)
使用する方法はありますか?ファイル名の拡張以内test
表現より具体的には、bash 条件式?
例えば:
[[ -f foo* ]] && echo 'found it!' || echo 'nope!';
...は出力します"いいえ!"foobar
ファイルが現在のディレクトリに存在するかどうか。
そして「var
いいね!」を追加します...
bar=foo*
[[ -f `echo $bar` ]] && echo 'found it!' || echo 'nope!';
...は出力します"それを見つけた!"ファイルが存在する場合foobar
、ただし、展開echo $bar
によって返されたファイルが 1 つだけの場合のみです。
答え1
以下では、ブロック特殊ファイル、文字特殊ファイル、ディレクトリ、シンボリックリンクなど、どのファイルにも glob が一致するかどうかを気にしないことを前提としています。
これは次のような場合の理想的な使用例ですfailglob
:
shopt -s failglob
if echo foo* &>/dev/null
then
# files found
else
# no files found
fi
または、ファイルが存在する場合にそのリストが必要な場合:
shopt -s failglob
files=(foo*)
if [[ "${#files[@]}" -eq 0 ]]
then
# no files found
else
# files found
fi
ファイルが見つからないというエラーの場合は、次のように簡略化できます。
set -o errexit
shopt -s failglob
files=(foo*)
# We know that the expansion succeeded if we reach this line
古い回答
ls
これはスクリプト内での(まれな!) 正当な使用法である可能性があります:
if ls foo* &>/dev/null
then
…
else
…
fi
あるいは、find foo* -maxdepth 0 -printf ''
.
答え2
に基づくこの答えshopt -s nullglob
を使用すると、ディレクトリが空の場合に何も返されないことを保証できます。
[[ -n "$(shopt -s nullglob; echo foo*)" ]] && echo 'found it!' || echo 'nope!';
答え3
完全を期すために、 を使用した例をいくつか示しますfind
。
#!/bin/bash
term=$1
if find -maxdepth 1 -type f -name "$term*" -print -quit | grep -q .; then
echo "found"
else
echo "not found"
fi
if [ -n "$(find -maxdepth 1 -type f -name "$term*" -print -quit)" ]; then
echo "found"
else
echo "not found"
fi
そしていくつかのテスト:
user@host > find -type f
./foobar
./bar/foo
./bar/bar
./find_prefixed_files.sh
./ba
user@host > ./find_prefixed_files.sh foo
found
found
user@host > ./find_prefixed_files.sh bar
not found
not found