0

I have a script on my mac where I'm trying to loop on the txt files inside a subfolder of my current location. This is myscript.sh:

cd /Users/Desktop/
for entry in $(pwd)/txt/*.txt 
do 
echo $entry
done

this prints a string of the path including *txt in it like /Users/Desktop/txt/*.txt I want to loop on the .txt files so I expect the echo $entry to print the names of the txt files but instead it prints /Users/Desktop/txt/*.txt

2

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
  • thanks, but why it doesn't match? although the path is correct and there are some txt files in it? – Tak Mar 30 '17 at 8:36
  • If you had files with an .txt suffix in the txt directory of your current working directory, then the paths of those files would be shown. The current working directory (returned by pwd) is the directory where you're currently at, not where the script lives. – Kusalananda Mar 30 '17 at 8:40
  • I've updated my question as in the beginning of the script I did cd but the echo prints the correct directory, so I'm not sure why it's not working? – Tak Mar 30 '17 at 8:44
  • That's what pwd does. The shell will resolve relative paths from the script's current directory anyway so $(pwd)/ should just be replaced with nothing. Or better yet take out the cd before the loop and just say for entry in /Users/Desktop/txt/*.txt (if you really genuinely have a directory named like that -- aren't you missing the user's account name?) – tripleee Mar 30 '17 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.