大网数据广告活动
服务器运维问答

Call rsync with args stored in a string

· 52CE 我爱测

This is the same script as the one cited in my mhddfs thread, I'd like to define the args according to some inputs, and call rasync afterwards. I currently came up with this but only the call to rsync is not working : #!/bin/bash…

问题原文

原帖链接 · JeanneD4RK · CC BY-SA 4.0

This is the same script as the one cited in my mhddfs thread, I'd like to define the args according to some inputs, and call rasync afterwards. I currently came up with this but only the call to rsync is not working :

#!/bin/bash

INCLUDE=""
EXCLUDE=""
USER=""
HOST=""
KEY=""
FORCE=false
SHUTDOWN=false
DESTINATION=""
LASTFULL=""

while getopts u:h:k:s:o:f:e:i: option
do
    case "${option}" in
        u) USER=${OPTARG};;
        i) INCLUDE=${OPTARG};;
        e) EXCLUDE=${OPTARG};;
        h) HOST=${OPTARG};;
        k) KEY=${OPTARG};;
        s) SHUTDOWN=true;;
        o) DESTINATION=${OPTARG};;
        f) FORCE=true;
    esac
done

if [ -z $USER ] || [ -z $HOST ] || [ -z $DESTINATION ]
then
    echo "Usage : $0 <-u : user> <-h : host> <-t : type> <-o : output directory> [-k : key] [-s : shutdown]"
    exit 1
fi

if [ ! -d "$DESTINATION/../Backup" ]
then
    if [ ! -d "$DESTINATION/Backup" ]
    then
        echo "Creating backup directory on target..."

        if ! mkdir "$DESTINATION/Backup"
        then
            echo "Could not create the backup directory. Exiting."
            exit 2
        fi
    fi
    DESTINATION="$DESTINATION/Backup"
fi

RSYNC_ARGS="-ravh -H --rsync-path=\"sudo rsync\" --append --progress --delete --safe-links"
if [ -f "$KEY" ]
then
    RSYNC_ARGS="$RSYNC_ARGS -e \"ssh -i $KEY\""
fi
if [ -f "$INCLUDE" ]
then
    echo "Including only files from $INCLUDE"
    RSYNC_ARGS="$RSYNC_ARGS --files-from=$INCLUDE"
fi
if [ -f "$EXCLUDE" ]
then
    echo "Excluding files from $EXCLUDE"
    RSYNC_ARGS="$RSYNC_ARGS --exclude-from=$EXCLUDE"
fi
if ! $FORCE
then
    LASTBACKUP=$(basename $(ls -td  $DESTINATION/*/ | sed "y/\t/\n/" | head -n 1 ) 2>/dev/null)
    echo "Processing backup based on --> $LASTBACKUP"
    RSYNC_ARGS="$RSYNC_ARGS --link-dest=../$LASTBACKUP"
else
    echo "Processing full backup"
fi

DESTINATION=$(echo "$DESTINATION/$(date '+%Y_%m_%d')" | sed "s#//#/#g")

rsync $RSYNC_ARGS $USER@$HOST:/ $DESTINATION 2> error.log

CODE=$?
if [ $CODE -eq 0 ]
then
    echo "Backup done : $DESTINATION"
    exit 0
else
    echo "Rsync stopped with code $CODE"
    exit $CODE
fi

I get

Rsync stopped with code 1

error.log contains

Unexpected remote arg : <correct username>@<correct host>:/

When I echo the rsync call, copy paste it, it works

I know that $RSYNC_ARGS is messing this up but I don't know how to call it properly. Any idea ?

已采纳解答

原帖链接 · Gordon Davisson · CC BY-SA 4.0

The shell parses quotes before expanding variables, so putting quotes in a variable's value doesn't do what you expect -- by the time they're in place, it's too late for them to do anything useful. See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail! for more details.

In cases like this, where you want to build a command's argument list dynamically, the best option is to store the arg list in an array. This way, the quotes get parsed when the array is created, each "word" gets stored as a separate array element, and if you reference the variable properly, the array elements get included in the command's argument list without any unwanted parsing:

rsync_args=(-ravh -H --rsync-path="sudo rsync" --append --progress --delete --safe-links)
if [ -f "$key" ]
then
    rsync_args+=(-e "ssh -i $key")
fi
if [ -f "$include" ]
then
    echo "Including only files from $include"
    rsync_args+=(--files-from="$include")
fi
# ... etc
rsync "${rsync_args[@]}" "$user@$host:/" "$destination" 2> error.log

Note that all the parentheses and += in the assignments; and double-quotes, braces, and [@] when using the array, are required for this to work right.

BTW, you may notice that I've used lowercased all the variable names. Using uppercase variable names in the shell is dangerous, because there are a number of them with special meaning to the shell and/or other programs, and accidentally reusing one of those can have unintended effects. In fact, $USER and $HOST are like this (they get initialized to the current local username and hostname); reusing them probably won't cause trouble, but it's better to just avoid the issue by using lower- or mixed-case variable names. But you might want to add user=$USER at the beginning of the script so it'll default to using the same username if -u isn't specified.

Also, I added double-quotes around the variable references that didn't have them. You can often get away without them, but it's a good idea to use them to avoid potential problems. I recommend running your scripts through shellcheck.net, since it's good at spotting common problems like this.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-10-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。