3

I want to write a shell script. I list my jpg files inside nested subdirectories with the following command line:

find . -type f -name "*.jpg"

How can I save the output of this command inside a variable and write a for loop for that? (I want to do some processing steps for each jpg file)

2 Answers 2

3

You don't want to store output containing multiple files into a variable/array and then post-process it later. You can just do those actions on the files on-the-run.

Assuming you have bash shell available, you could write a small script as

#!/usr/bin/env bash
#              ^^^^ bash shell needed over any POSIX shell because
#                   of the need to use process-substitution <()

while IFS= read -r -d '' image; do
    printf '%s\n' "$image"
    # Your other actions can be done here
done < <(find . -type f -name "*.jpg" -print0)

The -print0 option writes filenames with a null byte terminator, which is then subsequently read using the read command. This will ensure the file names containing special characters are handled without choking on them.

Sign up to request clarification or add additional context in comments.

Comments

1

Better than storing in a variable, use this :

find . -type f -name "*.jpg" -exec command {} \;

Even, if you want, command can be a full bloated shell script.

A demo is better than an explanation, no ? Copy paste the whole lines in a terminal :

cat<<'EOF' >/tmp/test
#!/bin/bash

echo "I play with $1 and I can replay with $1, even 3 times: $1"
EOF
chmod +x /tmp/test
find . -type f -name "*.jpg" -exec /tmp/test {} \;

Edit: new demo (from new questions from comments)

find . -type f -name "*.jpg" | head -n 10 | xargs -n1 command

(this another solution doesn't take care of filenames with newlines or spaces)

This one take care :

#!/bin/bash

shopt -s globstar

count=0

for file in **/*.jpg; do
    if ((++count < 10)); then
        echo "process file $file number $count"
    else
        break
    fi
done

7 Comments

Then, how can I select each jpg file separately without a for loop over the list of jpg files? Also, Can I write multiple commands inside the command {}?
Added simple for loop, better suitable for your needs
Use just the latest solution alone
I can not because I have to use the find command to get list of jpg images in nested subdirectories and do processing on the middle jpg images which have better quality.
He, I give you all what you need (3 solutions), time to test and read doc now ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.