[opensuse] bash test for empty dir
Guys, I stumbled across a neat use of ls -A for testing for an empty dir that I thought I would pass on: #!/bin/bash if [[ $(ls -A ${1}) ]]; then echo "the directory is not empty" else echo "the directory empty" fi If anybody has a better way, let me know. Thanks. -- David C. Rankin, J.D.,P.E. Rankin Law Firm, PLLC 510 Ochiltree Street Nacogdoches, Texas 75961 Telephone: (936) 715-9333 Facsimile: (936) 715-9339 www.rankinlawfirm.com -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org For additional commands, e-mail: opensuse+help@opensuse.org
Hello, On Thu, 20 Jan 2011, David C. Rankin wrote:
I stumbled across a neat use of ls -A for testing for an empty dir that I thought I would pass on:
#!/bin/bash
if [[ $(ls -A ${1}) ]]; then ^^^^ *BLAM* _ALWAYS_ QUOTE ARGUMENTS
And I'd prefer the more readable and portable if test -n "$(ls -A "$1")"; then or the even more portable if test "$(ls -A "$1" | wc -l)" -gt 0; then I'm not sure about the 'ls -A' though, so a if test "$(ls -a "$1" | wc -l)" -gt 2; then might be preferable, '-a' should be pretty portable. BTW: one might want to unset LS_OPTIONS and have a look at PATH before using just "ls" (and not /bin/ls). I'm glad I usually use perl for scripting that should be portable (or get's longer than a couple commands ;)
If anybody has a better way, let me know. Thanks.
On a related note: How to test for a directory having any direct subdirectories? In a somewhat explicit form: num_subdirs() { for dir; do nlinks=$(stat -c '%h' "$dir"); subdirs=$(( $nlinks - 2 )); ### printf "'%s' has %d subdirectories.\n" "$dir" "$subdirs"; echo "$subdirs"; test "$#" -eq 1 && return $subdirs; done } HTH & have fun! -dnh --
Mine had one where I think 4 machines were so intertwined that none would boot unless 2 of the others were up. And nothing else would boot till those were up. You are trapped in a maze of twisty little NFS-maps, all different. -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org For additional commands, e-mail: opensuse+help@opensuse.org
On Friday 21 January 2011 04:11:41 David Haller wrote:
num_subdirs() { for dir; do nlinks=$(stat -c '%h' "$dir"); subdirs=$(( $nlinks - 2 )); ### printf "'%s' has %d subdirectories.\n" "$dir" "$subdirs";
On the subject of portability, there are systems where it is possible to create a hardlink to a directory (e.g. Mac OS X), so your answer may not be correct on all systems. Anders -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org For additional commands, e-mail: opensuse+help@opensuse.org
participants (3)
-
Anders Johansson
-
David C. Rankin
-
David Haller