开发者

Can't find out why my bash script is exiting after access denied

I have a part of my script that does this:

  1. Removes everything in directory
  2. Force syncs from perforce that directory
  3. copies files from another directory to said directory, of which there are some conflicts that the source control prevent from being overwr开发者_如何学运维itten (which is expectable and what I want)

Before I would have just this:

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

Output:

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

So, it would do the stuff, and reach done. Then, I went and made a sort of check to make sure the directory exits like so:

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

But now the script just exits after the last of the Permission Denies, not hitting anything after, so the output is like this:

Output:

...
Permission Denied:file1
Permission Denied:file2

I'm not too savvy in the bash rules, so I just thought I'd post this question here since I couldn't find it. It seems that in the if, though, the fact that there are permission problems cause it to exit.


Other than syntax errors presumably introduced during cut'n'paste here, there's nothing wrong with that code, as shown by the following experiment:

#!/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!

When run, this outputs:

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

so you can see it's carrying on after the failure.

One piece of invaluable advice: when you're debugging bash scripts, put the line:

set -x

right up the top (after #!/bin/bash if it's there). That will cause it to output each command before executing it.

In fact, I always right my scripts starting with:

#!/bin/bash
#set -x

so I can just uncomment the second line for debugging purposes.

As an aside, I would code that as:

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>

but that's just because I don't like complicated if-then-else constructs.


you have to check write permissions

test -w / && echo "writable" 
test -w ~ && echo "writable" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜