具有特殊字符的变量的路径扩展和命令扩展

时间:2017-04-28 07:07:27

标签: bash macos shell

我已将代码块减少到以下示例。它在变量$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 中所有可能的字符?

data Person boss action = Person{
  salary  :: Float,
  subordonates :: [Person boss action],
  act :: action
  b :: boss
 }

资源:

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

1 个答案:

答案 0 :(得分:0)

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

请注意,您应该使用双引号,否则您的变量可能无法展开':

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

OS + Shell组合可以带来改变。可能的解决方案可能是:

  • 逃离空间,即" / Volumes / backup \ drive"
  • 修改 IFS (内部字段分隔符)的值;默认值是:[space] [tab] [newline] ==这些字符中的任何一个都会导致类似的问题...你采取这种方法然后记得保存,修改+使用,然后恢复原始值,因为你可以'破发'在你修补IFS之后会发生其他事情......

:)
戴尔

相关问题