循环输出空白变量 - SSH Bash

时间:2013-09-07 09:00:16

标签: bash shell ubuntu ssh

我正在编写一个脚本来帮助我在家用电脑和服务器之间同步文件。我遇到的一个问题是,当我运行for循环时,它输出空行。

其他一切似乎没问题,echo $REMOTE按预期列出所有文件及其完整路径。我尝试过不引用,引用,改变EOF和#34; EOF"到EOF等,但到目前为止没有任何工作。

以下是以下脚本:

function uploadDownload()
{
    if [ "$1" == "d" ]; then
        ssh -i ~/Dropbox/Business/aws/first.pem ubuntu@XXXX.194.202 << EOF
        echo $REMOTE

        for file in $REMOTE; do
            echo $file
        done
EOF
        #scp -r -i ~/Dropbox/Business/aws/first.pem ubuntu@XXXX.194.202:$REMOTE $LOCAL
    elif [ "$1" == "u" ]; then
        scp -r -i ~/Dropbox/Business/aws/first.pem $LOCAL ubuntu@XXXX.194.202:$REMOTE
    fi
}


if [ "$2" == "m" ]; then

    if [ -z "$3" ]; then
        echo "Please enter the local location of the files and provide an absolute path..."
        read LOCAL
        echo "Please enter the remote location of the files..."
        read REMOTE
        uploadDownload
    else
        LOCAL=$2
        if [ -z "$4" ]; then
            REMOTE=$3
        else
            REMOTE='ubuntu@XXXX.194.202:~/test/'
        fi  
        uploadDownload
    fi
else
    LOCAL='/home/will/Dropbox/Business/aws/files/binaryhustle/'
    REMOTE='/home/ubuntu/dev/binaryhustle/*'
    uploadDownload $1
fi

编辑:基于我已编辑uploadDownload函数的建议。我还应该注意,我在循环之外测试echo "$REMOTE";并且它什么也没有返回(不像没有引号,它返回的东西)。

function uploadDownload()
    {
        if [ "$1" == "d" ]; then
            ssh -i ~/Dropbox/Business/aws/first.pem ubuntu@54.252.194.202 << EOF
    for file in "/home/ubuntu/dev/binaryhustle"; do
    echo $file
    done
    EOF
            #scp -r -i ~/Dropbox/Business/aws/first.pem ubuntu@54.252.194.202:$REMOTE $LOCAL
        elif [ "$1" == "u" ]; then
            scp -r -i ~/Dropbox/Business/aws/first.pem $LOCAL ubuntu@54.252.194.202:$REMOTE
        fi
    }

3 个答案:

答案 0 :(得分:1)

尝试引用变量$file,因为它在发送到远程服务器之前已展开:

            echo $file

            echo \$file

或者更好

            echo \"\$file\"

答案 1 :(得分:1)

您可能需要查看unison。其强大的文件同步工具能够在ssh上工作。它没有做任何内容差异。

答案 2 :(得分:0)

归功于@konsolebox让我在那里中途,我通过将斜杠添加到文件来实现它,但是这不适用于&lt;&lt; EOF,仅<&lt;

function uploadDownload()
{
    if [ "$1" == "d" ]; then
            ssh -i ~/Dropbox/Business/aws/first.pem ubuntu@54.252.194.202 <<EOF
for file in "$REMOTE"; do
echo \$file
done
EOF
            #scp -r -i ~/Dropbox/Business/aws/first.pem ubuntu@54.252.194.202:$REMOTE $LOCAL
        elif [ "$1" == "u" ]; then
            scp -r -i ~/Dropbox/Business/aws/first.pem $LOCAL ubuntu@54.252.194.202:$REMOTE
        fi
    }