【发布时间】:2017-04-28 07:07:26
【问题描述】:
我已将我的代码块简化为以下示例。它在变量$backupPath 不包含空格字符时有效,但在包含空格字符时会失败。我花了大量时间研究下面的资源,并尝试了那里示例的许多变体。
我相信我可能需要一些转义字符和命令扩展的组合,也许使用$( ) 语法,但我似乎找不到正确的解决方案。
如何修改此代码,使其适用于$backupPath 中所有可能的字符?
backupFolderPath=$HOME"/Desktop/folder"
domain=".domain.com";
username="user";
destination[10]="subdomain";
backupPath[10]="/Volumes/backup drive";
i=10
findCommand[$i]='find '${backupPath[$i]}' -name "*partfilename*" -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f2- -d" "'
echo ${findCommand[$i]} #looks OK
filePath[$i]=`ssh $username@${destination[$i]}$domain "${findCommand[$i]}"`
echo ${filePath[$i]} # empty when $backupPath contains a space
rsync -avz $username@${destination[$i]}$domain:"${filePath[$i]}" $backupFolderPath # fails when $filePath is empty
资源:
Expansion of variable inside single quotes in a command in bash shell script
BASH Script to cd to directory with spaces in pathname
How to input a path with a white space?
How to set a variable to the output from a command in Bash?
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html
【问题讨论】:
-
可能使用
'findCommand[$i]='find "${backupPath[$i]}" ...可以解决您的问题吗?请注意,您没有给我们一些我们可以尝试的东西.. -
在您建议的行上用双引号替换
${backupPath[$i]}周围的单引号是不够的。我想不可能用ssh创建一个可重现的例子。有没有办法,或者我可以尝试另一个命令来达到同样的目的吗? -
对了,帖子的标题可以吗?
-
你应该通过shellcheck.net运行该代码...
-
您需要深入了解报价的工作原理。特别是,
backupFolderPath=$HOME"/Desktop/folder"应该写成backupFolderPath="$HOME/Desktop/folder"或backupFolderPath="$HOME"/Desktop/folder,你应该明白为什么。