How do create an alias in shell scripts?

有些话、适合烂在心里 提交于 2019-11-30 17:48:27

问题


Definin an alias on Linux system is very simple.

From the following example we see that: the I_am_only_ls_alias alias command gives us the output as ls command

 # alias I_am_only_ls_alias=ls
 # I_am_only_ls_alias

Output:

file   file1

But when I trying to do the same in bash script (define alias I_am_only_ls_alias), I get I_am_only_ls_alias: command not found.

Example of my bash script:

alias_test.bash

#!/bin/bash

alias I_am_only_ls_alias=ls

I_am_only_ls_alias

Run the bash script - alias_test.bash

/tmp/alias_test.bash

Output:

/tmp/: line 88: I_am_only_ls_alias: command not found

So, first I want to ask:

Why doesn't bash recognize the command I_am_only_ls_alias as an alias?

And what do I need to do in order to define aliases inside a bash script? Is it possible?


回答1:


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.




回答2:


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)




回答3:


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.



来源:https://stackoverflow.com/questions/24054154/how-do-create-an-alias-in-shell-scripts

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