How do create an alias in shell scripts?

£可爱£侵袭症+ 提交于 2019-12-01 00:49:23

From the bash man page:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

So this should work:

#!/bin/bash
shopt -s expand_aliases
alias I_am_only_ls_alias=ls
I_am_only_ls_alias

Scripts usually use functions, not aliases.

Barmar's answer is the correct one for including an alias, but it's likely that you'll actually find a Bash function to be more flexible/useful.

For example this is materially the same as the alias version, but can be expanded much more easily:

timp@helez:~/tmp$ cat test.sh
#!/usr/bin/bash

function i_am_only_an_ls_func {
  ls $@
}

i_am_only_an_ls_func
timp@helez:~/tmp$ ./test.sh
0600871h.html
[snip]
timp@helez:~/tmp$

The $@ is irrelavent in this example, but it means that anything after i_am_only_an_ls_func will be added after the ls command, since $@, $1, $2, etc contain the arguments to the function, much the same as for a normal script. (Note that $0 is still the name of the parent script not the function)

Aliases cannot be defined in shell script that you execute - their effect will be gone once shell process finished execution.

You can, however, define aliases in your ~/.bashrc or in separate shell script that you source from (but not execute!). In that case, aliases are imported into already running shell process, and thus survive and actually work as you would expect.

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