![bash에 접두사가 있는 하나 이상의 파일이 있는지 테스트하는 방법은 무엇입니까? 예를 들어 [[-f foo*]]](https://linux55.com/image/178564/bash%EC%97%90%20%EC%A0%91%EB%91%90%EC%82%AC%EA%B0%80%20%EC%9E%88%EB%8A%94%20%ED%95%98%EB%82%98%20%EC%9D%B4%EC%83%81%EC%9D%98%20%ED%8C%8C%EC%9D%BC%EC%9D%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%85%8C%EC%8A%A4%ED%8A%B8%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F%20%EC%98%88%EB%A5%BC%20%EB%93%A4%EC%96%B4%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
다음에서는 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