我使用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,同樣的錯誤!
我使用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,同樣的錯誤!
您的.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 usingshopt
.
所以,如果你想別名,在腳本工作,你必須做shopt -s expand_aliases
第一。或者只是使用shell函數而不是別名。
在通常的〜/ .bashrc文件的開頭可以發現兩條線爲:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
此行中止這無論如何都不會推薦包容腳本。對於可移植性問題,您通常會編寫完整的命令或在腳本中定義別名。
最簡單的答案是解決這個問題是做在你的腳本中的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
@anubhava:「亞層」是一個技術術語,似乎並不適用於此。我猜你的意思是這樣「調用的shell腳本」,但是在這種情況下,你只是簡單描述OP觀察,而不是解釋它的行爲。 – ruakh
在腳本中使用別名不是一個好習慣。改用功能。此外,製作腳本依賴於'.bashrc'不理想也是如此。看到這個帖子:https://unix.stackexchange.com/questions/1496/why-doesnt-my-bash-script-recognize-aliases – codeforester
可能重複的:https://stackoverflow.com/questions/30130954/alias-犯規,工作中-A-的bash腳本 – codeforester