move命令也在源目录中执行移动

时间:2017-07-20 05:14:49

标签: shell unix scripting

我编写了一个shell脚本来将文件从源目录移动到目标目录。

/home/tmp/ to /home/from/

移动正确,但显示消息

mv: /home/tmp/testfile_retry_17072017.TIF
/home/tmp/testfile_retry_17072017.TIF are identical.

如果源目录为空,则显示

mv: cannot rename /home/tmp/* to /home/from/*  

for /home/tmp/*

中的文件
if [ -f "$file" ]
then
    do 
        DIRPATH=$(dirname "${file}")
        FILENAME=$(basename "${file}")
#       echo "Dirpath = ${DIRPATH} Filename = ${FILENAME}"
        mv "${DIRPATH}/"${FILENAME} /home/from
        echo ${FILENAME} " moved to from directory" 
    done
else
    echo "Directory is empty"
fi

2 个答案:

答案 0 :(得分:0)

你的事情有点乱了:

for file in /home/tmp/*
if [ -f "$file" ]
then
    do 

当然"$file"将存在 - 您正在循环for file in /home/tmp/*。它看起来像你打算

for file in /home/tmp/*
do
    FILENAME=$(basename "${file}")
    if [ ! -f "/home/from/$FILENAME" ]  ## if it doesn't already exist in dest
    then

注意:POSIX shell包含参数扩展,可让您避免调用dirnamebasename。相反,您可以简单地使用"${file##*/}"作为文件名(只是说删除 left 到最后/的所有内容)。这是您需要的唯一扩展(因为您已经知道目标目录名称)。这样您就可以检查[ -f "$dest/${f##*/}" ]以确定/home/from

中是否存在您正在移动的同名文件

您可以使用以下优势:

src=/home/tmp           ## source dir
dst=/home/from          ## destination dir

for f in "$src"/*       ## for each file in src
do
    [ "$f" = "$src/*" ] && break  ## src is empty
    if [ -f "$dst/${f##*/}" ]   ## test if it already exists in dst
    then
        printf "file '%s' exists in '%s' - forcing mv.\n" "${f##*/}" "$dst"
        mv -f "$f" "$dst"       ## use -f to overwrite existing
    else
        mv "$f" "$dst"          ## regular move otherwise
    fi
done

有一个很好的资源可以检查名为ShellCheck.net的shell代码。只需在网页中输入您的代码(或粘贴它),它就会分析您的逻辑和变量使用情况,并让您知道问题的确定位置。

仔细看看,如果您有其他问题,请告诉我。

答案 1 :(得分:0)

你应该使用find代替/ home / tmp / *,如图所示。

Transaction
相关问题