[英]shell script, need help to check if file exists
I have two folders "downloads", and "files". 我有两个文件夹“下载”和“文件”。 I want to move all .txt files form downloads to files. 我想将所有.txt文件形式的下载内容移到文件中。 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. “ / Volumns / files”文件夹是另一台Ubuntu服务器上的共享文件夹。 I auto mount this folder when I login. 登录时会自动挂载此文件夹。 The address of this folder is "smb://ubuntunas/files". 该文件夹的地址是“ smb:// ubuntunas / files”。
still need to figure out why my code works for other folders but not this one. 仍然需要弄清楚为什么我的代码可用于其他文件夹,但不适用于此文件夹。
A compact version (note find ... -maxdepth 1
and cp -nv
) 精简版(请注意find ... -maxdepth 1
和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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.