Linux 在 bash 中定义一个类似函数的宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10186359/
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-08-06 05:49:37  来源:igfitidea点击:

define a function-like macro in bash

linuxbashubuntumacros

提问by a-z

Is it possible to define a macro-function in bash so when I write:

是否可以在 bash 中定义宏函数,所以当我写时:

F(sth);

bash runs this:

bash 运行这个:

echo "sth" > a.txt;

采纳答案by ormaaj

Arbitrary syntax can't be made to do anything. Parentheses are metacharacterswhich have special meaning to the parser, so there's no way you can use them as valid names. The best way to extend the shell is to define functions.

不能使任意语法做任何事情。括号是对解析器具有特殊意义的元字符,因此您无法将它们用作有效名称。扩展外壳的最好方法是定义函数。

This would be a basic echowrapper that always writes to the same file:

这将是一个echo始终写入同一个文件的基本包装器:

f() {
    echo "$@"
} >a.txt

This does about the same but additionally handles stdin - sacrificing echo's-eand -noptions:

这大致相同,但另外处理标准输入 - 牺牲echo's-e-n选项:

f() {
    [[ ${1+_} || ! -t 0 ]] && printf '%s\n' "${*-$(</dev/fd/0)}"
} >a.txt

Which can be called as

这可以称为

f arg1 arg2...

or

或者

f <file

Functions are passed arguments in the same way as any other commands.

函数以与任何其他命令相同的方式传递参数。

The second echo-like wrapper first tests for either a set first argument, or stdin coming from a non-tty, and conditionally calls printf using either the positional parameters if set, or stdin. The test expression avoids the case of both zero arguments and no redirection from a file, in which case Bash would try expanding the output of the terminal, hanging the shell.

第二个类似 echo 的包装器首先测试set first argument或来自非 tty 的 stdin,并使用位置参数(如果已设置)或 stdin 有条件地调用 printf。测试表达式避免了零参数和文件没有重定向的情况,在这种情况下,Bash 会尝试扩展终端的输出,挂起 shell。

回答by Emil Vikstr?m

F () {
  echo "" > a.txt
}

You don't use parentheses when you call it. This is how you call it:

调用时不使用括号。你是这样称呼它的:

F "text to save"

回答by yazu

Yes, only you should call it with F sth:

是的,只有你应该用F sth

F()
{
  echo "" > a.txt
}

Read more here.

在这里阅读更多。

回答by Robert Birdsall

This was answered long ago, but to provide an answer that satisfies the original request (even though that is likely not what is actually desired): This is based on Magic Aliases: A Layering Loophole in the Bourne Shellby Simon Tatham.

很久以前就回答了这个问题,但提供了一个满足原始请求的答案(即使这可能不是实际需要的):这是基于Magic Aliases: A Layering Loophole in the Bourne Shellby Simon Tatham。

F() { str="$(history 1)"; str=${str# *F(}; echo "${str%)*}"; } >a.txt
alias F='\F #'

$ F(sth)
$ cat a.txt
sth