a-z*_*a-z 7 linux bash macros ubuntu
是否有可能在bash中定义一个宏函数,所以当我写:
F(sth);
Run Code Online (Sandbox Code Playgroud)
bash运行这个:
echo "sth" > a.txt;
Run Code Online (Sandbox Code Playgroud)
orm*_*aaj 15
任意语法都无法做任何事情.括号是元字符,对解析器有特殊意义,因此您无法将它们用作有效名称.扩展shell的最佳方法是定义函数.
这将是一个echo总是写入同一文件的基本包装器:
f() {
echo "$@"
} >a.txt
Run Code Online (Sandbox Code Playgroud)
这大约相同,但另外处理stdin - 牺牲echo's -e和-n选项:
f() {
[[ ${1+_} || ! -t 0 ]] && printf '%s\n' "${*-$(</dev/fd/0)}"
} >a.txt
Run Code Online (Sandbox Code Playgroud)
这可以称为
f arg1 arg2...
Run Code Online (Sandbox Code Playgroud)
要么
f <file
Run Code Online (Sandbox Code Playgroud)
函数以与任何其他命令相同的方式传递参数.
第二个类似echo的包装器首先测试set第一个参数,或来自非tty的stdin,并使用位置参数(如果设置)或stdin有条件地调用printf.测试表达式避免了零参数和文件没有重定向的情况,在这种情况下,Bash会尝试扩展终端的输出,挂起shell.
F () {
echo "$1" > a.txt
}
Run Code Online (Sandbox Code Playgroud)
调用时不使用括号。你是这样称呼它的:
F "text to save"
Run Code Online (Sandbox Code Playgroud)