bash 脚本执行中的 rsync 未知选项

Kai*_*iya 4 bash ubuntu shell-script lubuntu

我正在尝试使用 rsync 通过本地网络将文件夹从我面前的计算机简单地同步到目标计算机。

#!/bin/bash

echo "This script will sync from my Macbook Dropbox/scripts/ folder to ruth@10.0.0.9 @ Norms house"

OPTIONS="--recursive --ignore-existing --progress"
SRC_DIR="~/Dropbox/scripts/"
DST_DIR="ruth@10.0.0.9:~/scripts/"
rsync "$OPTIONS" "$SRC_DIR" "$DST_DIR"
Run Code Online (Sandbox Code Playgroud)

给自己写权限

chmod +x nameofscript.sh
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它输出:

rsync: --recursive --ignore-existing --progress: unknown option
Run Code Online (Sandbox Code Playgroud)

如何正确存储这些选项并将其作为脚本运行?

fil*_*den 5

通过引用"$OPTIONS",shell 将其作为单个字符串传递给 rsync,因此 rsync 尝试查找名为 的单个选项"--recursive --ignore-existing --progress",该选项显然不存在,因为这是三个单独的选项。

这应该可以为你解决这个问题:

rsync $OPTIONS "$SRC_DIR" "$DST_DIR"
Run Code Online (Sandbox Code Playgroud)

更好的选择可能是使用 bash 数组来存储您的选项。

OPTIONS=(
    --recursive
    --ignore-existing
    --progress
)
# ...
rsync "${OPTIONS[@]}" "$SRC_DIR" "$DST_DIR"
Run Code Online (Sandbox Code Playgroud)

使用数组的优点是,如果需要的话,您可以引入包含空格的项目。