【发布时间】:2013-06-19 21:24:47
【问题描述】:
我有一个 Bash 脚本 (Cygwin),它使用一些带有空格的 Windows 路径。因此,我在变量定义中使用\ 转义了空间。
脚本中的所有内容都运行良好。但是,我需要将此变量作为参数传递给命令行可执行文件。当我这样做时,我的逃跑会变得一团糟。
示例非功能性脚本:
#!/bin/sh
# File paths
destinationPath="/cygdrive/c/Documents and Settings/Eric/My Documents/"
attachments="\n2013-12-12.pdf"
body="Test Body"
recipient="asdf@asdf.com"
# Prepare attachments
args=""
for file in $attachments ; do
file=${file//[ \\n]/}
touch $file
mv $file "$destinationPath/$file"
args="$args -a $destinationPath/$file"
done
# Send email
echo -e $body | email --from-addr nosender@mydomain.com --from-name "Automated CSS Downloader" --subject "Downloaded new file(s) \
from CSS" $args eric@mydomain.com
脚本的输出:
$ bash -x test.sh
+ destinationPath='/cygdrive/c/Documents and Settings/Eric/My Documents/'
+ attachments='\n2013-12-12.pdf'
+ body='Test Body'
+ recipient=asdf@asdf.com
+ args=
+ for file in '$attachments'
+ file=2013-12-12.pdf
+ touch 2013-12-12.pdf
+ mv 2013-12-12.pdf '/cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf'
mv: listing attributes of `2013-12-12.pdf': Invalid argument
+ args=' -a /cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf'
+ echo -e Test Body
+ email --from-addr nosender@mydomain.com --from-name 'Automated CSS Downloader' --subject 'Downloaded new file(s) from CSS' -a /cygdrive/c/Documents and Settings/Eric/My Documents//2013-12-12.pdf eric@mydomain.com
email: WARNING: Email address 'and' is invalid. Skipping...
email: FATAL: Could not open attachment: /cygdrive/c/Documents: No such file or directory
因此,如您所见,路径中的转义空格并未在 $args 变量中导出。我假设错误出现在“args = ...”行上。但我不确定如何转义 $destinationPath 以确保保留转义字符。
我尝试在destinationPath 中使用双引号(没有转义空格),但无济于事。如果我尝试在 args= 行中使用双引号 $destinationPath,那么输出也会被一堆额外的引号搞砸。
我怎样才能让它工作?我尝试过使用 $IFS 变量,但我真的不知道我在用它做什么,似乎也无法让它与它一起工作,尽管我怀疑该解决方案与 $国际金融服务公司。
【问题讨论】:
-
您是否尝试过双重转义空格?例如。
Documents\\\ and\\\ -
我试过了,但遇到了几个问题:1)我的 mv 不起作用,因为它试图将文件移动到 Documents\\ 和 \\ (即:bash 吞下一个escape),然后电子邮件表达式中 $args 的扩展变为: -a '/cygdrive/c/Documents\' 'and\' 'Settings/Eric/My\' Documents/AJ/CSS//2013-06- 21.pdf。在每个空间中,多个 ' 的 b/c 不起作用。
-
也许您可以将destinationPath 带入双引号并删除转义空格?和你一样休息
-
我已经尝试了几乎所有我能想到的组合。如果我使用双引号 desinationPath(没有转义字符串),则电子邮件扩展不带引号,然后再次中断。我已经使用功能齐全的示例脚本编辑了我的原始问题。
-
大胆猜测,但请尝试将
$destinationPath/$file替换为\"$destinationPath/$file\",看看是否有帮助
标签: bash variables escaping ifs