【问题标题】:How to make a alias to rsync?如何为rsync创建别名?
【发布时间】:2016-10-25 10:52:28
【问题描述】:

我经常使用这个命令来同步远程和本地。

rsync -xyz --foo=bar some_files user@remote.com:remote_dir

所以我想用一个别名来简化这个,像这样:

up_remote () {
    local_files=${@:1:$((${#}-1))}  # treat argument[1:last-1] as local files
    remote_dir="${@[$#]}" # treat argument[last] as remote_dir
    echo $local_files
    echo $remote_dir
    rsync -xyz --foo=bar "$local_files" user@remote.com:"$remote_dir"
}

但如果我传递三个或更多参数,它将不起作用:

up_remote local1 local2 remote_dir

当我用set -x 调试这个函数时,我发现这个函数会像这样生成rsync

rsync -xyz --foo=bar 'local1 local2' user@remote.com:"$remote_dir"

注意local1 local2 周围的单引号(')。如果我删除这些单引号 rsync 将正常工作,但我不知道该怎么做。

欢迎任何建议。

【问题讨论】:

  • 当然,这是一个解决方案,并且会起作用。

标签: linux rsync scp


【解决方案1】:

你只需要去掉$local_files周围的双引号:

up_remote () {
  local_files=${@:1:$((${#}-1))}
  remote_dir="${@:$#}"
  rsync -xyz --foo=bar $local_files a.b.com:"$remote_dir"
}

请注意,我还更改了选择 remote_dir 的方式,无法在我的 bash 版本中使用。

【讨论】:

  • 您是否尝试在local_files 中传递两个或更多参数?像这样:up_remote file1 file2 /tmpup_remote file* /tmp
  • 是的,这两种调用方式都运行良好。你使用的是什么版本的 bash,我的函数有什么输出?
  • 你是对的。我之前在zsh 用过,是我的错。它适用于我的bash。谢谢。
【解决方案2】:

不是一个真正的答案,但我用 perl 做到了,而且它有效:

#!/usr/bin/perl

use strict;
use warnings;

my @args = @ARGV;
my $files;

my $destination=pop(@args);

foreach(@args){
    $files.="'".$_."' ";
}

system("rsync -xyz --foo=bar $files user\@remote.com:$destination");

您可以在路径中复制此脚本或为其创建别名。

【讨论】:

  • 这将失败,文件名包含空格。为什么不使用类似 String::ShellQuote 的东西?
  • 你是正确的空白,一种解决方法是在 foreach 中添加单引号(在我的答案中编辑)
  • 现在,如果您的文件名有单引号,它会中断。目的地也一样。正如我所说,有模块可以为您进行转义
  • 对不起,但我不知道如何正确使用 bash。祝你好运;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 2011-02-28
  • 2020-02-04
  • 2020-05-23
  • 1970-01-01
  • 2012-02-16
  • 2021-09-19
相关资源
最近更新 更多