Set expand_alias when shopt not available?

混江龙づ霸主 提交于 2021-02-10 15:28:13

问题


I'm trying to use an alias in a shell script I'm writing, but it is not working.

The alias:

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

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?

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

EDIT: as some people are having trouble understanding what I mean, this answer has an example.


回答1:


Don't use aliases in scripts. A function does the same job better.

ts() { gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }' "$@"; }
  • 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 the ts command available to subprocesses (where the shell they run is also bash).


来源:https://stackoverflow.com/questions/47331495/set-expand-alias-when-shopt-not-available

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!