디렉토리에 파일이 없는지 테스트하고 싶습니다. 그렇다면 일부 처리를 건너 뛸 것입니다.
나는 다음을 시도했다.
if [ ./* == "./*" ]; then
echo "No new file"
exit 1
fi
다음과 같은 오류가 발생합니다.
line 1: [: too many arguments
해결책 / 대안이 있습니까?
답변
if [ -z "$(ls -A /path/to/dir)" ]; then
echo "Empty"
else
echo "Not Empty"
fi
또한 디렉토리가 이전에 존재하는지 확인하는 것이 좋습니다.
답변
껍데기를 구할 필요가 없습니다. read
와 함께 사용할 수도 있습니다 find
. 경우 find
의 출력이 비어있는, 당신은 돌아갑니다 false
:
if find /some/dir -mindepth 1 | read; then
echo "dir not empty"
else
echo "dir empty"
fi
휴대용이어야합니다.
답변
if [ -n "$(find "$DIR_TO_CHECK" -maxdepth 0 -type d -empty 2>/dev/null)" ]; then
echo "Empty directory"
else
echo "Not empty or NOT a directory"
fi
답변
#!/bin/bash
if [ -d /path/to/dir ]; then
# the directory exists
[ "$(ls -A /path/to/dir)" ] && echo "Not Empty" || echo "Empty"
else
# You could check here if /path/to/dir is a file with [ -f /path/to/dir]
fi
답변
현재 작업 디렉토리 (.)에서 작업을 수행합니다.
[ `ls -1A . | wc -l` -eq 0 ] && echo "Current dir is empty." || echo "Current dir has files (or hidden files) in it."
또는 같은 명령이 더 읽기 쉽도록 세 줄로 나뉩니다.
[ `ls -1A . | wc -l` -eq 0 ] && \
echo "Current dir is empty." || \
echo "Current dir has files (or hidden files) in it."
그냥 교체 ls -1A . | wc -l
와 ls -1A <target-directory> | wc -l
다른 대상 폴더에서 실행해야하는 경우.
편집 : 나는 교체 -1a
와 함께 -1A
(@Daniel 설명을 참조)
답변
다음을 사용하십시오.
count="$( find /path -mindepth 1 -maxdepth 1 | wc -l )"
if [ $count -eq 0 ] ; then
echo "No new file"
exit 1
fi
이 방법으로의 출력 형식과 독립적입니다 ls
. -mindepth
디렉토리 자체를 건너 뛰고 -maxdepth
하위 디렉토리를 재귀 적으로 방어하여 속도를 높입니다.
답변
배열 사용하기 :
files=( * .* )
if (( ${#files[@]} == 2 )); then
# contents of files array is (. ..)
echo dir is empty
fi