简体   繁体   English

别名不在Shell脚本中执行

[英]Aliases are not executed in Shell script

In my bashrc file I have n number of alias. 在我的bashrc文件中,我有n个别名。 But, If I execute via shell script, it will not give expected output. 但是,如果我通过shell脚本执行,则不会给出预期的输出。 Why it will be like this. 为什么会这样。 Is there any way to solve this problem. 有什么办法可以解决这个问题。

Thanks in advance. 提前致谢。

Aliases (as set using alias name=value ) are only used in an interactive context, ie when the user types something on the command line. 别名(使用alias name=value在交互式上下文中使用,即,当用户在命令行上键入某些内容时。 They are never executed by a script (unless a non-interactive shell is explicitly tweaked to do this using the shopt -s expand_aliases ): 它们永远不会由脚本执行(除非使用shopt -s expand_aliases显式地调整了非交互式外壳才能执行此操作):

#!/bin/bash
alias ttt=date
ttt  # will fail!

Sourcing a configuration script which defines aliases will not change anything about this. 提供定义别名的配置脚本不会对此进行任何更改。 Scripts simply will not execute aliases. 脚本根本不会执行别名。

To achieve what you want, rewrite your aliases as shell functions: 要实现所需的功能,请将别名重写为shell函数:

#!/bin/bash
ttt() {
  date
}
ttt  # will succeed!

Shell functions can replace aliases completely but there are some more things to know and consider: Shell函数可以完全替换别名,但还有更多需要了解和考虑的事项:

  1. You can even export shell functions so that child shells also have them. 您甚至可以导出外壳函数,以便子外壳也具有它们。 Use export -f ttt for this. 为此使用export -f ttt
  2. Shell functions can override other commands so they can interfere in the behaviour of scripts (unlike aliases which are never executed in scripts). Shell函数可以覆盖其他命令,因此它们可以干扰脚本的行为(与别名不同,别名从未在脚本中执行)。 Keep this in mind in case you plan to override things like cd or ls . 请记住这一点,以防您打算覆盖cdls类的东西。
  3. An overridden built-in of the shell (eg cd ) can still be reached by calling it as builtin cd /my/direc/tory . 仍然可以通过将其称为builtin cd /my/direc/tory覆盖的外壳(例如cd )。
  4. Argument handling is quite different from aliases (and much more powerful). 参数处理与别名完全不同(并且功能更强大)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM