NikosDim
NikosDim

Reputation: 1508

Loop through files in Mac terminal

I am trying to write a simple loop that will loop through the files the current directory and just print the file names.

I tried that:

#!/bin/bash    
FILES=/Users/nick/Desktop/*.jpg
    for f in $FILES
    do
        echo $f
    done

but it didn't work. Running ./script it just printed "/Users/nick/Desktop/*.jpg". No errors

I am running this on a MacBook Pro 10.10.4

Thanks

Upvotes: 33

Views: 51301

Answers (4)

Leonid Usov
Leonid Usov

Reputation: 1598

for f in /Users/nick/Desktop/*.jpg; do echo $f; done

Edit Actually, I think that this comment by @KyleBurton is very clever and should be taken into account since it explains why a result like OP's could be observed.

Upvotes: 72

atErik
atErik

Reputation: 1077

Single/one line based solution, (to use/run in Terminal shell):
find "./" -not -type d -maxdepth 1 -iname "*.jpg" -print0 | while IFS= read -r -d $'\0' fileName ; do { echo "$fileName"; }; done; unset fileName;

for your/OP's case, change the "./" into "/Users/nick/Desktop/"

To use in a script file:

#!/bin/bash
find "./" -not -type d -maxdepth 1 -iname "*.jpg" -print0 | while IFS= read -r -d $'\0' fileName ; do {
    echo "$fileName";
    # your other commands/codes, etc
};
done;
unset fileName;

or, use (recommended) below codes as script:

#!/bin/bash
while IFS= read -r -d $'\0' fileName ; do {
    echo "$fileName";
    # your other commands/codes, etc
};
done < <(find "./" -not -type d -maxdepth 1 -iname "*.jpg" -print0);
unset fileName;

Please checkout my other answer here for description of what code does what function.
As i have shown link to a description, i can avoid repeating same in here.

Upvotes: 1

Manikandan
Manikandan

Reputation: 1234

You can use simple find command to get all things, with type file ..

find . type f

Upvotes: -1

Abdul
Abdul

Reputation: 51

Try this, please:

for f in $(ls /Users/nick/Desktop/*.jpg); 
do echo $f; 
done

Upvotes: 4

Related Questions