gpt4 book ai didi

bash - 如何将带空格的不带引号的字符串作为带引号的参数传递?

转载 作者:行者123 更新时间:2023-11-29 09:27:45 25 4
gpt4 key购买 nike

最好用一个例子来解释。我正在围绕邮件命令编写一个简单的包装器(我的 .bashrc 中的一个函数)。

这是我当前无法正常工作的功能:

function email_me() { echo "$@" | mail -s "\"$@\"" myaddress@email.com; }

这是我想要的用法 - 这将发送一封主题和正文都设置为 testing 1 2 3 的电子邮件。请注意,我特别不想手动输入引号。

~$ email_me testing 1 2 3

因此我希望字符串替换像这样发生:

echo "testing 1 2 3" | mail -s "testing 1 2 3" myaddress@email.com

但是无论我尝试什么,就好像 -s 参数没有引号一样,并且将主题为 "testing 的电子邮件发送给以下收件人:1, 2、3 和 myaddress@email.com

如何使 -s 参数将“testing 1 2 3”视为单个字符串?

最佳答案

我建议使用

function email_me() { printf %s\\n "$*" | mail -s "$*" myaddress@email.com; }
  • "$*" 确实是在一个字符串中包含所有参数的特殊变量
  • 使用 printf 而不是 echo 可以避免 -n -e 和任何其他实现的意外echo 支持。

不过,在某些情况下,您必须引用 email_me 的参数以避免通配并保留空格:

email_me 2 * 2 = 4
[sends you all file names in current directory]
email_me a b
[sends "a b" with only one space]

关于bash - 如何将带空格的不带引号的字符串作为带引号的参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com