Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through files in Mac terminal

Tags:

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

like image 329
NikosDim Avatar asked Aug 03 '15 22:08

NikosDim


People also ask

How do I iterate through a file in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I iterate over a directory in bash?

This fits here: How do I loop through only directories in bash? Solid array under bash, (accepting spaced dirnames): dirs=(/tmp/*/);dirs=("${dirs[@]%/}");dirs=("${dirs[@]#/tmp/}") , then printf "%s\n" "${dirs[@]}" or for dir in "${dirs[@]}" ;do ...

How do you go to files on a Mac?

Just press Command-O in your app, navigate to the file, select it, and click Open or press Return. If you want to view a file when you're in an Open dialog, you can select and it press the space bar to view it in Quick Look.


2 Answers

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

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

like image 118
Leonid Usov Avatar answered Oct 11 '22 16:10

Leonid Usov


Try this, please:

for f in $(ls /Users/nick/Desktop/*.jpg);  do echo $f;  done 
like image 36
Abdul Avatar answered Oct 11 '22 16:10

Abdul