0

我的脚本中有一部分是这样做的:

  1. 删除目录中的所有内容
  2. 从 perforce 该目录强制同步
  3. 将文件从另一个目录复制到所述目录,其中存在一些冲突,源代码控制防止被覆盖(这是可以预料的,也是我想要的)

在我有这个之前:

...
cp <source path> <dest path>
echo done copying
...
echo done

输出:

...
Permission Denied:file1
Permission Denied:file2
done copying
...
done

所以,它会做的事情,并完成。然后,我进行了某种检查以确保目录退出如下:

if[ -d sourcepath ]
      then 
       if [ -d destpath ]
           then
              cp <source path> <dest path>
           else
              echo problem with dest
              exit 1
        fi
    else
        problem with source
       exit 1
fi

但是现在脚本只是在最后一个 Permission Denies 之后退出,之后没有命中任何内容,所以输出是这样的:

输出:

...
Permission Denied:file1
Permission Denied:file2

我对 bash 规则不太了解,所以我只是想我会在这里发布这个问题,因为我找不到它。但是,似乎在 if 中,存在权限问题的事实导致它退出。

4

2 回答 2

4

除了可能在此处剪切'n'粘贴期间引入的语法错误之外,该代码没有任何问题,如以下实验所示:

#!/bin/bash

rm -rf sourcepath destpath
mkdir sourcepath
mkdir destpath
touch sourcepath/xyz
touch destpath/xyz
chmod 000 destpath/xyz

if [ -d sourcepath ]
      then
       if [ -d destpath ]
           then
              cp sourcepath/xyz destpath/xyz
           else
              echo problem with dest
              exit 1
        fi
    else
       echo problem with source
       exit 1
fi
echo Woohoo!

运行时,输出:

cp: cannot create regular file `destpath/xyz': Permission denied
Woohoo!

所以你可以看到它在失败后继续进行。

一条非常宝贵的建议:当您调试bash脚本时,请输入以下内容:

set -x

就在顶部(#!/bin/bash如果它在那里)。这将导致它在执行之前输出每个命令。

事实上,我总是正确地从以下开始编写脚本:

#!/bin/bash
#set -x

所以我可以取消注释第二行以进行调试。

顺便说一句,我将其编码为:

if [[ ! -d sourcepath ]] ; then
    problem with source
    exit 1
fi
if [[ ! -d destpath ]] ; then
    problem with dest
    exit 1
fi
cp <source path> <dest path>

但这只是因为我不喜欢复杂的if-then-else结构。

于 2010-09-10T02:50:39.120 回答
0

你必须检查写权限

test -w / && echo "writable" 
test -w ~ && echo "writable" 
于 2010-09-10T02:54:27.600 回答