linux - Iterating with ls and checking with -f doesn't work -


i have piece of code should work, doesn't. want iterate through files , subdirectories of directories given in command line , see 1 of them file. program never entries in if statement.

for in $@;do     j in `ls $i`;do        if [ -f $j ];then           echo $j file!        fi     done done 

things can go wrong approach. way.

for in "$@" ;     j in "$i"/* ;        if [ -f "$j" ];           echo "$j regular file!"        fi     done done 

changes :

  • quoted "$@" avoid problems file paths containing spaces, newlines.

  • used shell globbing in inner loop, parsing ls output not idea (see http://mywiki.wooledge.org/parsingls)

  • double-quoted variable expansion inside test, once again allow files spaces, newlines.

  • added "regular" in output, because specific test operator tests (e.g. exclude files correspond devices, fifos, not directories).

you simplify bit if inclined :

for in "$@" ;     j in "$i"/* ;        ! [ -f "$j" ] || echo "$j regular file!"     done done 

if want use find, need make sure list files @ depth of 1 level (or else results different code). can way :

find "$@" -mindepth 1 -maxdepth 1 -type f -exec echo "{} file" \; 

please note still bit different, globbing (by default) excludes files start period. adding shopt -s dotglob loop-based solution allow globbing consider files, should make both solutions operate on same files.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -