当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - Creating a pathname to check a file doesn't exist there / Permission denied error

问题描述:

Hello from a Linux Bash newbie!

I have a list.txt containing a list of files which I want to copy to a destination($2). These are unique images but some of them have the same filename.

My plan is to loop through each line in the text file, with the copy to the destination occurring when the file is not there, and a mv rename happening when it is present.

The problem I am having is creating the pathname to check the file against. In the code below, I am taking the filename only from the pathname, and I want to add that to the destination ($2) with the "/" in between to check the file against.

When I run the program below I get "Permission Denied" at line 9 which is where I try and create the path.

for line in $(cat list.txt)

do

file=$[ basename $line ]

path=$[ $2$file ]

echo $path

if [ ! -f $path ];

then

echo cp $line $2

else

echo mv $line.DUPLICATE $2

fi

done

I am new to this so appreciate I may be missing something obvious but if anyone can offer any advice it would be much appreciated!

网友答案:

Submitting this since OP is new in BASH scripting no good answer has been posted yet.

DESTINATION="$2"

while read -r line; do
  file="${line##*/}"
  path="$2/$file"
  [[ ! -f $path ]] && cp "$line" "$path" || mv "$line" "$path.DUP"
done < list.txt

Don't have logic for counting duplicates at present to keep things simple. (Which means code will take care of one dup entry) As an alternative you get uniq from list.txt beforehand to avoid the duplicate situation.

网友答案:

@anubhava: Your script looks good. Here is a small addition to it to work with several dupes.
It adds a numer to the $path.DUP name

UniqueMove()
{
    COUNT=0
    while [ -f "$1" ]
    do 
        (( COUNT++ )) 
        mv -n "$1" "$2$COUNT"
    done
}

while read -r line; do
  file="${line##*/}"
  path="$2/$file"
  [[ ! -f $path ]] && cp "$line" "$path" || UniqueMove "$line" "$path.DUP"
done < list.txt
分享给朋友:
您可能感兴趣的文章:
随机阅读: