Reputation: 75
I'm trying to copy one file to multiple destinations with a bash script. I need loop through a text file to read the destinations and then copy the file to the target.
I tried this:
while read -r tpath
do
cp -p test.file "$tpath"
done < destination.txt
It does copy the file to all destinations in the file, but I get the following error...
cp: cannot create regular file `': No such file or directory
Can someone tell me what I'm doing wrong or suggest a better way to do it?
Upvotes: 1
Views: 1131
Reputation: 6995
Try this :
while IFS= read -r tpath
do
[[ "$tpath" ]] || continue # Ignore empty lines
if
[[ -d "$tpath" ]]
then
cp -p test.file "$tpath"
else
echo "Invalid target directory: $tpath"
fi
done < destination.txt
This will prevent empty lines or non-existent directories from being considered.
As an aside, the [[ "$tpath" ]]
returns 0 ("true" in shell semantics) if the variable contains a non-null value, and a non-zero value otherwise. It does the same thing as [[ -n "$tpath" ]]
. The continue
keyword causes the loop to skip to the next iteration, bypassing the rest of the loop. The ||
logical operator is a (lazy) OR logical operator : it will execute the statement on the right only if the statement on the left is false. The result of that line is that if tpath
is empty, the loop will silently skip to the next iteration without executing the rest of the body.
Upvotes: 1