如何让别名传播到另一个shell脚本

时间:2016-04-13 12:07:25

标签: shell

我知道它适用于文件 .bashrc 中的别名指令。 但是,shell脚本 ln_hook

#!/bin/sh
#filename: ln_hook

## http://stackoverflow.com/questions/3648819/how-to-make-symbolic-link-with-cygwin-in-windows-7
## https://cygwin.com/cygwin-ug-net/using-cygwinenv.html
## https://cygwin.com/cygwin-ug-net/using.html#pathnames-symlinks
# export CYGWIN="winsymlinks" # ln -s: The shortcut style symlinks with file extension '.lnk'
# export CYGWIN="winsymlinks:native" # ln -s: plain text file

ln_hook(){ 
    if [[ "-s" == "$1" ]]; then
        cmd /C mklink /H "$(cygpath -aw "$3")" "`cygpath -aw "$2"`"
    else
        echo -e "\033[32m >> $* \033[0m"
        ln "$*"
    fi
}
alias ln='ln_hook'
type ln

(type ln)


# cannot propagate to another shell script

./test_ln

$(dirname $0)/test_ln

## . ./ln_hook
## type ln

和另一个shell脚本:

#!/bin/sh
#filename: test_ln

type ln

然后运行. ./ln_hook,输出:

ln_hook
ln 是 `ln_hook' 的别名
ln 是 `ln_hook' 的别名
ln 是 /usr/bin/ln
ln 是 /usr/bin/ln

在运行其他脚本时是否有解决方法使别名生效?

1 个答案:

答案 0 :(得分:0)

进入Bash手册和谷歌后,export -f function_name就是我想要的。

感谢Etan Reisner有关函数递归的建议和示例代码如下:

#!/bin/bash --posix
# Avoid an error about function xx() statement on some os, e.g. on ubuntu, Syntax error: "(" unexpected 
# http://ubuntuforums.org/archive/index.php/t-499045.html 

#########################################################################################################
# << A example about exporting a function >>
# hook ln and propagate it to other scripts to pollute the environment of subsequently executed commands
#########################################################################################################

## https://stackoverflow.com/questions/3648819/how-to-make-symbolic-link-with-cygwin-in-windows-7
## https://cygwin.com/cygwin-ug-net/using-cygwinenv.html
## https://cygwin.com/cygwin-ug-net/using.html#pathnames-symlinks
# export CYGWIN="winsymlinks" # ln -s: The shortcut style symlinks with file extension '.lnk'
# export CYGWIN="winsymlinks:native" # ln -s: plain text file

## ln_hook
function ln(){ 
    if [[ "-s" == "$1" ]]; then
        cmd /C mklink /H "$(cygpath -aw "$3")" "`cygpath -aw "$2"`"
    else
        echo -e "\033[32m >>ln $* \033[0m"
        command ln "$*"
    fi
}

## Cannot propagate alias to other scripts
## alias ln='ln_hook'

## export -f ln=ln_hook ## ln_hook.sh: 第 23 行:export: ln=ln_hook: 不是函数

## http://docstore.mik.ua/orelly/unix3/upt/ch29_13.htm
## https://stackoverflow.com/questions/1885871/exporting-a-function-in-shell
export -f ln

echo&&echo "[^-^] After trying ln_hook"

echo -n "main shell: " && type ln

echo -n "subshell: " && (type ln)


echo&&echo "[^-^] Run an external script"

echo 'type ln' > test_ln.sh
./test_ln.sh  
# $(dirname $0)/test_ln.sh


## . ./ln_hook
echo 'You can try: `type ln`, which will output: ln 是函数...'

此处DemoBash shell editor and execute online