将文件移动到另一个目录时无法 cd 到目录错误

将文件移动到另一个目录时无法 cd 到目录错误

我编写了以下代码,将 2 分钟前创建的所有跟踪文件移动到单独的目录中。现在,当我在脚本中硬编码源路径和目标路径时,它工作正常;但是当我将它们作为变量传递时,我收到错误消息。以下是我的代码:

##THIS SCRIPT WILL MOVE ALL THE TRACE FILES CREATED BEFORE 2 MINUTES TO A SEPARATE DIRECTORY
cd /home/adhikarisubir/test/basic_unix  //MY TRACE_BKP.SH FILE EXISTS HERE
#TRACE_PATH=/home/adhikarisubir/test/basic_unix
#BKUP_PATH=/home/adhikarisubir/test_bkp
MINUTES=$1  #IT WILL GET THE NUMBER OF MINUTES FROM THE COMMAND LINE
TRACE_PATH=$2   #INSTEAD OF HARD-CODING TAKING PATHS AS VARIABLE
BKUP_PATH=$3    #^^
echo $MINUTES   
echo $BKUP_PATH
echo $TRACE_PATH
cd $TRACE_PATH
echo $pwd

for i in `find . -cmin +$MINUTES -name "*.trc"`  ##FINDING FILES WITH EXTENSTION .TRC WHICH ARE OLDER THAN GIVEN MINUTES
do
echo "Moving files $i, size `du -h $i`, which are older than $MINUTES minutes"
echo $i
mv $i $BKUP_PATH
done

我正在运行代码如下:

adhikarisubir@ubuntu:~/test/basic_unix$ sh trace_bkp.sh 2 home/adhikarisubir/test/basic_unix home/adhikarisubir/test_bkp

错误输出为:

2
home/adhikarisubir/test_bkp
home/adhikarisubir/test/basic_unix
trace_bkp.sh: 11: cd: can't cd to home/adhikarisubir/test/basic_unix 

Moving files ./elnc.trc, size 0 ./elnc.trc, which are older than 2 minutes
./elnc.trc
mv: cannot move ‘./elnc.trc’ to ‘home/adhikarisubir/test_bkp’: No such file or directory
Moving files ./ph.trc, size 0   ./ph.trc, which are older than 2 minutes
./ph.trc
mv: cannot move ‘./ph.trc’ to ‘home/adhikarisubir/test_bkp’: No such file or directory

答案1

重写:

#!/bin/bash

minutes=$1
trace_path=$2
bkup_path=$3

if [[ ! -d "$trace_path" ]]; then
    echo "Error: trace_path '$trace_path' is not a directory" >&2
    exit 1
fi
if [[ ! -d "$bkup_path" ]]; then
    echo "Error: bkup_path '$bkup_path' is not a directory" >&2
    exit 1
fi

echo "Moving files which are older than $minutes minutes"
find "$trace_path" -cmin +"$minutes" -name "*.trc" -exec mv -v -t "$bkup_path" '{}' \+

笔记:

  • 你不需要去cd任何地方
    • 如果您想将目录更改为脚本所在的位置,请执行以下操作:cd "$(dirname "$0")"
  • "$variables"除非你知道什么时候该引号,否则总是引用你的
  • 不要使用 UPPER_CASE_VARS:有一天你会不小心写PATH=foo然后想知道为什么你的脚本坏了
  • 验证用户输入
  • find可以对找到的文件进行一些操作。
  • mv有选项,检查其手册页

相关内容