MacOS 上 rsync 腳本中的環境變數出現空格問題

MacOS 上 rsync 腳本中的環境變數出現空格問題

我有一個 Bash 腳本,計劃運行它來進行日常備份(我的 HOME 是 /Volumes/Norman Data/me):

#!/bin/bash

# Halt the script on any errors.
set -e

# Remote server where
remote_server="example.com"

# Destination Folder on Remote Server
target_path="backup/"

# User (with sshy key) on remote server
usr="me"


# ${HOME} evaluates to '/Volumes/Norman Data/me'
# A list of absolute paths to backup. 
include_paths=(
  # "~/.ssh"
  # "~/.bash_history"
  "${HOME}/.bash_profile"
  # "~/.vimrc"
  # "~/.gitconfig"
  # "~/.gitignore"
  # "~/.zshrc"
  # "~/Artifacts"
  "${HOME}/Documents" 
  "--exclude=remote"
  # "~/Downloads"
  # "~/Desktop"
  # "~/Pictures"
  # "~/Projects --exclude 'remote'"
  # "~/Movies"
)

# A list of folder names and files to exclude.
exclude_paths=(
  ".bundle"
  "node_modules"
  "tmp"
)

# Passing list of paths to exclude
for item in "${exclude_paths[@]}"
do
  exclude_flags="${exclude_flags} --exclude=${item}"
done

# Passing list of paths to copy
for item in "${include_paths[@]}"
do
  include_args="${include_args} '${item}'"
done


str="rsync -auvzP ${exclude_flags} ${include_args} ${usr}@${remote_server}:${target_path}"
echo "Running: ${str}"
${str}

運行結果是:

building file list ... 
rsync: link_stat "/Volumes/Norman" failed: No such file or directory (2)
rsync: link_stat "/Volumes/Norman Data/me/Data/me/.bash_profile" failed: No such file or directory (2)
rsync: link_stat "/Volumes/Norman" failed: No such file or directory (2)
rsync: link_stat "/Volumes/Norman Data/me/Data/me/Documents" failed: No such file or directory (2)
0 files to consider

sent 29 bytes  received 20 bytes  32.67 bytes/sec
total size is 0  speedup is 0.00
rsync error: some files could not be transferred (code 23) at 
/BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-52/rsync/main.c(996) [sender=2.6.9]

據我所知,我的價值空間HOME正在引起問題。我認為引用它"${HOME}/.bash_profile"可以解決空格問題。看起來,有點。我的意思是,我從中獲得的價值echo "Running: ${str}"

rsync -auvzP  --exclude=.bundle --exclude=node_modules --exclude=tmp  '/Volumes/Norman Data/me/.bash_profile' '/Volumes/Norman Data/me/Documents' --exclude=remote [email protected]:backup/

當我直接在終端機中運行它或將其貼到腳本中(代替 )時${str},它會按預期工作。

似乎無法弄清楚我在這裡缺少什麼。任何人都可以透露一些資訊嗎?

** 腳本改編自https://gitlab.com/ramawat/randomhacks/blob/master/backup_script.txt

答案1

您使用數組來保存參數是正確的,但您不應該嘗試將數組展平為單個字串,因為在作為命令運行時需要將其拆分為單詞,並且會出現引用問題。

只需在整個腳本中使用數組即可,例如將命令累積在數組中cmd

cmd=(rsync -auvzP)
for item in "${exclude_paths[@]}"
do  cmd+=("--exclude=${item}")
done
for item in "${include_paths[@]}"
do  cmd+=("${item}")
done

cmd+=("${usr}@${remote_server}:${target_path}")

set -x
"${cmd[@]}"

set -x如果您在末尾使用,您將看到 shell 如何將單字保留到單一參數中。它向您顯示了它正在使用的概念引用:

+ rsync ... '/Volumes/Norman Data/me/.bash_profile' ...

相關內容