1
#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
    cd /home/Sud/Minimal\ Packages/All/
    if [ -d $line ]
    then
        cp $line*.rpm /home/Sud/NewFolder/rpms/
    else
        echo $line>>/home/Sud/NewFolder/notfound.txt
    fi
done < "$1"

I am trying to run the above code to

  1. Read a text file line by line
  2. Search a folder if there is a directory by that name
    • a) if yes; copy contents of that directory to another directory
    • b) if not, copy the directory name to another text file.

Each time I run the script, it copies all names to notfound.txt even though they are present in the folder I'm searching.

Where am I going wrong?

  • It looks like you have white-spaces in the name. Have you tried if [ -d "$line" ] instead? – UVV Mar 29 '16 at 10:56
  • I tried running the cp line in shell. It works even if I use 'cp $line*.rpm destination/' instead of using 'cp "$line*.rpm" destination/' – sudhansh_ Mar 29 '16 at 11:39
  • How about cp "$line"/*.rpm destination/ – iruvar Mar 29 '16 at 11:48
  • @1_CR that didn't work for me. – sudhansh_ Mar 29 '16 at 12:01
0

Could you please try to put every usage of $line in double quotes to handle white-spaces properly?

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
cd /home/Sud/Minimal\ Packages/All/
if [ -d "$line" ]
then
    cp "$line*.rpm" /home/Sud/NewFolder/rpms/
else
    echo "$line" >> /home/Sud/NewFolder/notfound.txt
fi
done < "$1"
  • That didn't work. Everything is still going to 'notfound.txt' – sudhansh_ Mar 29 '16 at 11:33
  • @SudhanshAggarwal I gave it a try and seemed to have worked for me. Could you please check if you have trailing slash in directories? i.e. path/to/mydir/ instead of path/to/mydir. – UVV Mar 29 '16 at 11:42
  • @SudhanshAggarwal you also do cd /home/Sud/Minimal\ Packages/All/ in your script. Is your directory list relative to that path? – UVV Mar 29 '16 at 11:43
  • Yes, directory list is relative to /home/Sud/Minimal\ Packages/ I also removed the trailing slashes from the 'cp' line, didn't give me any different result. – sudhansh_ Mar 29 '16 at 12:00
  • @SudhanshAggarwal Like I said the script worked just fine for me. Could you please provide some items from your list that supposed to work? – UVV Mar 29 '16 at 12:07
0
if cp "$line"*.rpm destination/ ; then
    echo $line "successful!"
else
    echo $line "not found!"
    echo "$line">> /home/Sud/notfound.txt
fi

This worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.