When you give the shell a globbing pattern that doesn't match any file names, the globbing pattern will not be expanded. In your case, this means that the echo
in the loop outputs the pattern itself.
Alternative implementation of your script:
cd /Users/Desktop || exit 1
for entry in txt/*.txt; do
test -e "$entry" && echo "$entry"
done
This implementation will exit with a non-zero exit code if the cd
fails. It will then not use pwd
since it's unnecessary. It will get a list of names matching the pattern and will iterate over these. In each iteration, it tests to make sure there is actually something in the filesystem that has that name before outputting the name to standard output.
If you want the echo
inside the lop to output the full path of the files, use echo "/Users/Desktop/$entry"
, or even better:
dir="/Users/Desktop"
cd "$dir" || exit 1
for entry in txt/*.txt; do
test -e "$entry" && printf '%s/%s\n' "$dir" "$entry"
done
http://stackoverflow.com/questions/31797856/loop-through-files-in-mac-terminal
– Kamaraj Mar 30 '17 at 08:35echo "$entry"
. See also http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-value – tripleee Mar 30 '17 at 08:50