bash에 접두사가 있는 하나 이상의 파일이 있는지 테스트하는 방법은 무엇입니까? 예: [[-f foo*]]

bash에 접두사가 있는 하나 이상의 파일이 있는지 테스트하는 방법은 무엇입니까? 예: [[-f foo*]]

사용하는 방법이 있나요?파일 이름 확장~ 이내에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

다음에서는 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

관련 정보