在没有商店时设置expand_alias? [英] Set expand_alias when shopt not available?
问题描述
我正在尝试在正在编写的Shell脚本中使用别名,但无法正常工作.
I'm trying to use an alias in a shell script I'm writing, but it is not working.
别名:
alias ts="awk '{ print strftime(\"[%Y-%m-%d %H:%M:%S]\"), \$0 }'"
运行脚本时,出现以下错误:
When I run the script, I get the following error:
./copyTask.sh: ts: not found
在互联网上闲逛,似乎我需要启用 expand_aliases
shell选项,但是我没有安装 shopt
...有什么办法吗?我可以启用别名扩展,而无需使用 shopt
或创建另一个rootfs映像?
Sooping around on the internet, it seems that I need to enable the expand_aliases
shell option, but I don't have shopt
installed... Is there any way I can enable alias expansion without using shopt
or creating another rootfs image?
我正在使用 ash
外壳.而 awk
是BusyBox v1.25.0 awk
.
I'm using the ash
shell. And awk
is BusyBox v1.25.0 awk
.
注意:别名是在时间戳前面加上命令的简单方法:
NOTE: The alias is an easy way to prepend a timestamp to a commmand:
$ echo "foo" | ts
[2005-06-23 11:52:32] foo
由于某些人难以理解我的意思,此答案有一个例子.
as some people are having trouble understanding what I mean, this answer has an example.
推荐答案
不要在脚本中使用别名.函数执行相同的功能更好.
Don't use aliases in scripts. A function does the same job better.
ts() { gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' "$@"; }
- 这适用于任何POSIX shell,包括根本不支持别名的shell.
- 这适用于非交互式外壳,而无需显式启用别名支持.
- 这可以通过别名无法扩展的方式来扩展(可以将条件逻辑放入函数中;可以将参数置于函数中非尾部的位置;等等).
- 在bash中,可以将函数导出到环境中:
export -f ts
将使ts
命令可用于子进程(它们运行的shell也是bash) - This works with any POSIX shell, including ones that don't support aliases at all.
- This works with noninteractive shells without needing to enable alias support explicitly.
- This can be extended in ways that aliases can't (you can put conditional logic inside functions; you can put arguments in non-tail positions in functions; etc).
- In bash, functions can be exported to the environment:
export -f ts
will make thets
command available to subprocesses (where the shell they run is also bash).
这篇关于在没有商店时设置expand_alias?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!