1

I have two folders "downloads", and "files". I want to move all .txt files form downloads to files. before moving them to files folder, I check to see if it already exists in the "files" folder. If does not exist, then i will move them.

but for some reasons, my scripts always return file does not exists.

#!/bin/sh

SOURCE_PATH="/Users/johnqin/Downloads/*.txt"
DEST_PATH="/Volumns/files/"

ls -l $SOURCE_PATH > /dev/null 2>&1

# check if there are any .txt files
if [ "$?" = "0" ]; then

    # loop through all .txt files
    for file in $SOURCE_PATH
    do
        # get only file name
        fname=`basename $file`
        #echo $fname

        targetFile="$DEST_PATH$fname"
        # echo $targetFile

        # check if this file exist in the target folder
        if [ -e "$targetFile" ]
        then
            echo "$fname exists, do nothing"
            # will do nothing
        else
            echo "$fname does not exist, move the file over"
            # will move file over
        fi
    done
else
    echo "did not find file"
fi  

UPDATE:

I think I know what the problem is. my code is fine. "/Volumns/files" folder is a shared folder on another Ubuntu server. I auto mount this folder when I login. The address of this folder is "smb://ubuntunas/files".

still need to figure out why my code works for other folders but not this one.

1 Answer 1

1

A compact version (note find ... -maxdepth 1 and cp -nv)

Code:

#!/bin/bash
set -eu

readonly source=/home/bobah
readonly destination=/home/bobah/tmp
while read line; do
  echo 'name: ['${line}'], basename: ['${line##*/}']'
  cp -nv ${line} ${destination}
done < <(find ${source} -maxdepth 1 -name '*.cpp')

Output:

name: [/home/bobah/abc.cpp], basename: [abc.cpp]
name: [/home/bobah/test.cpp], basename: [test.cpp]
`/home/bobah/test.cpp' -> `/home/bobah/tmp/test.cpp'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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