如何调整bash函数,以便可以省略双引号? [英] How can I adjust my bash function such that I can omit the double-quotes?

查看:44
本文介绍了如何调整bash函数,以便可以省略双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整天中,我经常输入以下内容:

git stash push -u -m短语作为消息"

我宁愿键入:

stpu一些短语作为消息

因此,在此答案的帮助下,我在〜./bashrc :

  function stpu(){git stash push -u -m" $ {@}"} 

现在,我可以输入 stpu短语作为消息" ,这与我想要的非常接近.

如何调整功能以省略双引号?

我尝试了许多不同的变体(添加更多的转义双引号,添加单引号等),但没有使其起作用.

解决方案

如果您使用"$ *" 代替"$$"

这会将所有参数连接成一个字符串,并用空格分隔(默认情况下;如果已覆盖,则为 IFS 中的第一个字符). -m 期望在其后跟随一个字符串(而不是每个单词使用单独的参数),因此这正是它想要的.


这不可靠,最好只使用引号.

安全性

如果想使用提交消息,请考虑以下示例:在参数名称中使$(rm -rf〜)安全以进行安全修复.如果此字符串未用引号引起来,则该命令将在您的函数启动之前执行(这很有意义:只有在知道其参数列表之后才能调用该函数),因此您的函数无法对其进行修复.

正确性

或者,作为另一个示例:仅处理与* .csv 匹配的文件-如果未加引号,则可以将 *.csv 替换为CSV文件列表运行命令的目录中存在的文件.同样,这是在您的函数启动之前 发生的,因此函数内部没有任何东西可以阻止它.

Throughout the day, I type something like this frequently:

git stash push -u -m "some phrase as a message"

I would prefer to type instead:

stpu some phrase as a message

So with help from this answer, I created a function in my ~./bashrc:

function stpu() {
  git stash push -u -m "${@}"
}

Now I'm able to type stpu "some phrase as a message", which is pretty close to what I want.

How can I adjust my function such that I can omit the double-quotes?

I've tried many different variations (adding more double-quotes that are escaped, adding single-quotes, etc) but haven't gotten it to work.

解决方案

You can sometimes omit the quotes if you use "$*" instead of "$@"

This will concatenate all your arguments together into a single string, separated with spaces (by default; the first character in IFS, if it's been overridden). -m expects a single string to follow it (instead of a separate argument per word), so this is exactly what it wants.


This is not reliable, and it's better to just use the quotes.

Security

Consider as an example if you want to use the commit message: Make $(rm -rf ~) safe in an argument name for a security fix. If this string is unquoted, the command is executed before your function is ever started (which makes sense: a function can't be called until after its argument list is known), so there's nothing your function can do to fix it.

Correctness

Or, as another example: Process only files matching *.csv -- if it's not quoted, the *.csv can be replaced with a list of CSV files that exist in the directory where you ran the command. Again, this happens before your function is ever started, so nothing inside the function can prevent it.

这篇关于如何调整bash函数,以便可以省略双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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