bash 如何在一行上定义一个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38595559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:56:19  来源:igfitidea点击:

How to define a function on one line

bashfunctionsyntax

提问by Steffen

Often when moving files around, I need to do the opposite later. So in my .bashrc I included this working code:

通常在移动文件时,我需要稍后做相反的事情。所以在我的 .bashrc 中我包含了这个工作代码:

rmv() {
  mv /${1##*/} ${1%/*}
}

Now I wonder why I can't write this as a single liner. This is what I tried:

现在我想知道为什么我不能把它写成单行。这是我尝试过的:

rmv() {mv /${1##*/} ${1%/*}}

If I do so, I get this error:

如果我这样做,我会收到此错误:

-bash: .bashrc: line 1: syntax error near unexpected token `{mv'

回答by ruakh

In Bash, {is not automatically recognized as a special/separate token from what's around it. So you need whitespace between {and mv.

在 Bash 中,{不会自动将其识别为与周围事物不同的特殊/单独标记。所以你需要在{和之间留空格mv

Additionally:

此外:

  • }needs to be the start of a command; so if it's not on its own line, you need ;to terminate the previous command.
  • It's a best practice to always use double-quotes around any parameter expansion, since otherwise you'll get bizarre behaviors when the parameters include whitespace or special characters.
  • }需要是命令的开始;因此,如果它不在自己的行上,则需要;终止上一个命令。
  • 最佳做法是始终在任何参数扩展周围使用双引号,否则当参数包含空格或特殊字符时,您会出现奇怪的行为。

So:

所以:

rmv() { mv "/${1##*/}" "${1%/*}" ; }