嵌套if:参数太多了?

FLX*_*FLX 1 bash shell

出于某种原因,此代码会产生问题:

source="/foo/bar/"
destination="/home/oni/"

if [ -d $source ]; then
        echo "Source directory exists"
        if [ -d $destination ]; then
                echo "Destination directory exists"
                rsync -raz --delete --ignore-existing --ignore-times --size-only --stats --progress $source $destination
                chmod -R 0755 $destination
        else
                echo "Destination directory does not exists"
        fi
else
        echo "Source directory does not exists"
fi
Run Code Online (Sandbox Code Playgroud)

它出错了:

Source directory exists
/usr/bin/copyfoo: line 7: [: too many arguments
Destination directory does not exists
Run Code Online (Sandbox Code Playgroud)

我之前在bash中使用嵌套的if语句没有问题,我忽略了什么简单的错误?

谢谢!

ini*_*all 5

语法看起来确实正确.在dash/bash中工作.

您是否更改了此示例的目标目录的名称?如果您的真实姓名包含例如空白,则最好引用测试变量.

if [ -d "$destination" ]; then 
Run Code Online (Sandbox Code Playgroud)

(无论如何,我会离开目标目录检查,因为如果丢失,rsync将创建目录.如果你在同一台计算机而不是通过网络复制,我也会留下rsync的-z压缩参数.)

更新:

这对你有用吗?(你必须改变路径)

#!/bin/bash

source="/tmp/bar/"
destination="/tmp/baz/"

test -d "$source" || {
    echo "$source does not exist"
    exit
}

rsync -ra \
--delete \
--ignore-existing --ignore-times --size-only \
--stats --progress "$source" "$destination"

if [ "$?" -gt 0 ]; then
    echo "Failure exit value: $?"
fi
Run Code Online (Sandbox Code Playgroud)