【问题标题】:Path expansion and command expansion from variables with special characters特殊字符变量的路径扩展和命令扩展
【发布时间】: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,你应该明白为什么。

标签: bash macos shell


【解决方案1】:

最简单的解决方案,从路径中删除/替换“空格”。正如您“发现”的那样,文件名/路径中的特殊字符需要特别注意,并且解决起来可能非常耗时...

请注意,您应该使用双引号,否则您的变量可能不会“扩展”:

"${backupPath[$i]}" ## this should work vs 
'${backupPath[$i]}' ## this should NOT work

OS + Shell 组合可以发挥作用。可能的解决方案可能是:

  • 转义空间,即“/Volumes/backup\ drive”
  • 修改IFS(内部字段分隔符)的值;默认值为: [space][tab][newline] == 这些字符中的任何一个都会导致类似的问题...如果您采用这种方法,请记住保存,修改+使用,然后恢复原始值,因为您可以在你修改 IFS 之后“打破”其他东西......

:)
戴尔

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2011-10-17
    • 1970-01-01
    • 2012-04-08
    • 2012-06-30
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多