0

I can not make this simple script work in bash

# Works
for f in *; do
    for j in $f/Attachments/*.pdf; do 
        echo "$j"
    done;
done

# Doesn't work  
for f in *; do
    for j in $f/Attachments/*.pdf; do 
        if [ ! pdfinfo "$j" &> /dev/null ]; then
            echo "$j"
        fi
    done;
done

I have read 10+ guides, and I cannot understand why this script lists a bunch of random directories.

It should:

  1. List folders in the current directory
  2. In each folder it should list all PDF-files in the subdirectory Attachments
  3. For each file it should check if it is corrupt, and if so print it
Esben Eickhardt
  • 3,183
  • 2
  • 35
  • 56
  • 1
    The problem isn't the `for` loops, it's that the condition in the `if` statement is garbled. See ["Checking the success of a command in a bash `if [ .. ]` statement"](https://stackoverflow.com/questions/36371221/checking-the-success-of-a-command-in-a-bash-if-statement). – Gordon Davisson Sep 29 '22 at 18:32

1 Answers1

1

What you want could be achieved by this code snippet:

for f in */Attachments/*.pdf; do
    if ! pdfinfo "$f" &>/dev/null; then
        echo "$f"
    fi
done

In your code, for f in * iterates through all files (including directories). If you want directories only, you must have used for f in */. Like that:

for d in */; do
    for f in "$d"Attachments/*.pdf; do
        [[ -f $f ]] || continue
        if ! pdfinfo "$f" &>/dev/null; then
            echo "$f"
        fi
    done
done
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17