Home > Enterprise >  Linux multiline command with for
Linux multiline command with for

Time:03-09

I want to test and compare files in two folders. For this purpose, I used the next command

for FILE in folder_one/*; do
    test -f folder_one_arch/$FILE && echo $FILE " exists" || echo $FILE " not exists"
    cmp -s $FILE folder_one_arch/$FILE && echo "same" || echo "different";
done

but this command is not working, from where is the problem occuring?

CodePudding user response:

The problem comes from $FILE: it contains a path while you were expecting a file.

I propose you the following approach: have two variables, PATH which is the variable in the for loop and FILE which is only the file basename.

for PATH in folder_one/*; do
    echo "PATH is $PATH "
    FILE=${PATH##*/}
    echo "FILE is now $FILE"
    test -f folder_one_arch/$FILE && echo $FILE " exists" || echo $FILE " not exists"
    cmp -s $PATH folder_one_arch/$FILE && echo "same" || echo "different";
done

See https://mywiki.wooledge.org/BashFAQ/073

  • Related