如何传递包含引号/空格的脚本参数? [英] How do I pass on script arguments that contain quotes/spaces?

查看:94
本文介绍了如何传递包含引号/空格的脚本参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写可以在任何命令之前添加的脚本notify-finish.完成后,它将运行以下参数指定的命令,然后在命令完成后向用户发送电子邮件.这就是我所拥有的:

I'm trying to write a script notify-finish that can be prepended to any command. When done, it will run the command given by the arguments following, then email the user when the command is complete. Here's what I have:

PROG=$1
# Run command given by arguments
$@
ECODE=$?
echo -e "Subject: `hostname`: $PROG finished\r\nTo: <$USER>\r\n\r\nExited with $ECODE\r\n" | sendmail $USER

这在大多数情况下都有效,但是当参数包含空格时,引号会被删除.

This works most of the time, but when arguments contain spaces, the quoting is stripped off.

工作示例:

notify-finished rsync -avz source/ user@remote:dest/

失败示例:

notify-finished rsync -avz -e 'ssh -c blowfish' source/ user@remote:dest/

在第二种情况下,$@扩展为rsync -avz -e ssh -c blowfish source user@remote:dest/,缺少单引号.它不能用于双引号,也不能用于$*.

In the second case, $@ is expanded out to rsync -avz -e ssh -c blowfish source user@remote:dest/, missing the single quotes. It does not work with double-quotes either, nor with $*.

阅读其他文章后,我尝试将命令放入数组中,但出现了完全相同的问题:

After reading other posts I tried putting the command in an array, but I get the exact same issue:

CMD=(notify-finished rsync -avz -e 'ssh -c blowfish' source/ user@remote:dest/)
${CMD[@]}

我该如何处理所有参数?

How do I make this work for all arguments?

推荐答案

使用"$@" 带有引号:

prog="$1"
"$@"
ecode="$?"
echo "$prog exited with $ecode"

这将按原样传递每个参数.如果您不包括引号,则会根据$IFS将每个元素拆分:

This will pass each argument exactly as it was received. If you don't include the quotes, each element will be split according to $IFS:

  • "$@"类似于"$1" "$2" "$3" ...,将每个元素作为单独的参数传递.
  • "$*"类似于"$1 $2 $3 ...",将所有串联的元素作为单个参数传递
  • $*$@类似于$1 $2 $3 ...,将空白中的每个元素分解,扩展所有glob,并将每个结果单词作为单独的元素($IFS)传递.
  • "$@" is like "$1" "$2" "$3" ..., passing each element as a separate argument.
  • "$*" is like "$1 $2 $3 ...", passing all elements concatenated as a single argument
  • $* and $@ is like $1 $2 $3 ..., breaking up each element on whitespace, expanding all globs, and passing each resulting word as a separate element ($IFS).

对于数组,例如"${array[@]}""${array[*]}"

这篇关于如何传递包含引号/空格的脚本参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆