linux的脚本进入目录,shell进入目录自动执行脚本

经常在编译文件的时候需要导入一些环境变量,这个时候如果要修改bashrc的话通用性不好,如果不修改bashrc的话,经常忘记导入比如PATH等环境变量,所以现在折腾出如下脚本,当进入目录时如果发现此脚本存在自动执行脚本

使用方法在bashrc中加入如下函数,当用户调用到cd的时候此函数会覆盖shell内建cd

简单版本:

function cd()

{         builtin cd $1

for file in dragon_dir.rc

do

if [ -f $file ]

then

source $file

fi

done

}

builtin 是调用内置命令,command 是调用PATH 里的命令

dragonDir .dragonDir dragondir .dragondir是执行文件的名称,如果当前目录下找到这些文件那么会依顺序执行当前文件

不过简单版本只能包含脚本,还存在两个问题:

问题1:当一个程序重复进入目录的时候有可能存在dragon_dir.rc被重复包含执行的现象

问题2:退出目录时无法清理环境,当多个编程环境切换时环境混乱

高级版本:

export DragonDir_file=dragon_dir.rc

function expect_open_dragon_dir_execuld()

{

builtin cd $1

source $DragonDir_file

export dragon_dir=${PWD}

echo "dragon into $dragon_dir"

}

function expect_open_dragon_dir()

{

expect -c "

spawn $SHELL

send \"expect_open_dragon_dir_execuld $1\n\"

send_user \"dragon_dir source $1/$DragonDir_file \n\"

interact

"

}

function cd()

{

p=$(realpath $1)

if [ "$dragon_dir"x != ""x ] && [ "$(echo $p|grep $dragon_dir)"x == ""x ]

then

echo "dragon exit $dragon_dir"

exit

fi

if [ -f "$p/$DragonDir_file" ] && [ "$dragon_dir"x != "$p"x ]

then

expect_open_dragon_dir $p

else

builtin cd $p

fi

}使用方法与简单版本一样,将此段脚本放入bash.rc中,可以修改一下DragonDir_filet路径名称,重启shell环境(DragonDir_file是目录下执行脚本的路径,在环境目录下放入此脚本就跟Makefile一样,只要cd进入,就会自动包含环境,离开时自动退出环境)

注:高级版本依赖expect如果没有情调用sudo apt-get install expect

高级版本依赖realpath如果没有请调用sudo apt-get install realpath

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值