简体   繁体   中英

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

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

编辑实际上我认为@KyleBurton 的这个评论非常聪明,应该考虑在内,因为它解释了为什么可以观察到这样的结果。

Try this, please:

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

您可以使用简单的 find 命令来获取所有内容,类型为 file ..

find . type f

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM