我已经编写了一个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/* 对于/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发布于 2017-07-20 13:28:37
你的东西有点乱了:
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包含允许您避免调用dirname和basename的参数扩展。相反,您可以简单地使用"${file##*/}"作为文件名(这只是表示删除从左侧到(并包括)最后一个/的所有内容)。这是您唯一需要的扩展(因为您已经知道目标目录名)。这使您可以检查[ -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有一个很棒的资源可以用来检查您的shell代码,称为。只需在网页中输入(或粘贴)你的代码,它就会分析你的逻辑和变量使用,让你知道哪里发现了问题。
仔细检查一下,如果你还有其他问题,请告诉我。
发布于 2017-07-20 15:22:52
您应该使用find而不是/home/tmp/*,如下所示。
for file in $(find /home/tmp/ -type f)
do
if [ -f "$file" ]
then
DIRPATH=$(dirname "${file}")
FILENAME=$(basename "${file}")
# echo "Dirpath = ${DIRPATH} Filename = ${FILENAME}"
mv "${DIRPATH}/"${FILENAME} /home/from
echo ${FILENAME} " moved to from directory"
else
echo "Directory is empty"
fi
donehttps://stackoverflow.com/questions/45205710
复制相似问题