2017-06-06 61 views
1

我使用Mac和我有:为什么bash别名在脚本中不起作用?

$cat .bashrc|grep la 
alias la='ls -la' 

然后我试图使用它在脚本:

$cat ./mytest.sh 
#!/bin/bash 
la 

它运行,并说这是不可能找到啦:

./mytest.sh: line 2: la: command not found 

这是为什么?我尝试了Mac和Linux,同样的错误!

+2

@anubhava:“亚层”是一个技术术语,似乎并不适用于此。我猜你的意思是这样“调用的shell脚本”,但是在这种情况下,你只是简单描述OP观察,而不是解释它的行为。 – ruakh

+0

在脚本中使用别名不是一个好习惯。改用功能。此外,制作脚本依赖于'.bashrc'不理想也是如此。看到这个帖子:https://unix.stackexchange.com/questions/1496/why-doesnt-my-bash-script-recognize-aliases – codeforester

+0

可能重复的:https://stackoverflow.com/questions/30130954/alias-犯规,工作中-A-的bash脚本 – codeforester

回答

6

您的.bashrc仅供交互式shell使用。 https://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files说:

Invoked non-interactively

When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi 

but the value of the PATH variable is not used to search for the filename.

As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.

正如你所看到的,也没什么可说.bashrc那里。您的别名根本不存在于脚本中。


但即使.bashrc被读,有another problem

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt .

所以,如果你想别名,在脚本工作,你必须做shopt -s expand_aliases第一。或者只是使用shell函数而不是别名。

1

在通常的〜/ .bashrc文件的开头可以发现两条线为:

# If not running interactively, don't do anything 
[ -z "$PS1" ] && return 

此行中止这无论如何都不会推荐包容脚本。对于可移植性问题,您通常会编写完整的命令或在脚本中定义别名。

1

最简单的答案是解决这个问题是做在你的脚本中的2个重要的东西 - 或者它不会的工作,如果你只是做一两件事。

#!/bin/bash -i 

# Expand aliases defined in the shell ~/.bashrc 
shopt -s expand_aliases 

在此之后,您在〜/定义的.bashrc他们会在你的shell脚本(giga.sh或any.sh),并将这些脚本中的任何函数或子shell提供您的别名。

如果你不这样做,你会得到一个错误:

your_cool_alias: command not found 
相关问题