问题
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 thets
command available to subprocesses (where the shell they run is also bash).
来源:https://stackoverflow.com/questions/47331495/set-expand-alias-when-shopt-not-available