LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1019|回复: 2

.bashrc 中定义的 function 在其他 script 中怎么不能用?

[复制链接]
发表于 2010-3-17 18:50:04 | 显示全部楼层 |阅读模式
小的纯属业余学习(未入门),还请各位大侠 详细解释!谢谢!!
.bashrc 中定义的 function 在其他 script 中怎么不能用?
在 .bashrc里定义了一个function ,这样用户每次进shell都可以应用它。
新建脚本中引用该function,可报错:
./test: line 5: addem: command not found
./test: line 6: multem: command not found
./test: line 7: divem: command not found
The result of adding them is:
The result of multiplying them is:
The result of dividing them is:
但是我在cli直接应用该function,却可以的。
[root@i temp]# divem 10 2
5
[root@i temp]# addem 10 2
12
[root@i temp]# multem 10 2
20
我的root's .bashrc :
$ cat .bashrc
# .bashrc
# Source global definitions
       if [ -r /etc/bashrc ]; then
                  . /etc/bashrc
       fi
. /temp/myfuncs
$
我的function
$ cat /temp/myfuncs
# my script functions
function addem {
   echo $[ $1 + $2 ]
}
function multem {
   echo $[ $1 * $2 ]
}
function divem {
   if [ $2 -ne 0 ]
   then
      echo $[ $1 / $2 ]
   else
      echo -1
   fi
}
新建的脚本:
$ cat test
#!/bin/bash
# using a function defined in the .bashrc file
value1=10
value2=5
result1=`addem $value1 $value2`
result2=`multem $value1 $value2`
result3=`divem $value1 $value2`
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
echo "The result of dividing them is: $result3"




后来 在 新建的脚本中,指定了一行:
. /temp/myfuncs就可以了正常执行脚本了:
[root@i ~]# /temp/test
The result of adding them is: 15
The result of multiplying them is: 50
The result of dividing them is: 2
可是我看的书里面说:Even without sourcing the library file, the functions worked perfectly in the shell script. 
我的理解,书中大意就是说把一个function放到某用户的.bashrc中,就可以被该用户在任何调用。而且书中的例子也说明是可以的。可是在我的centos5中,就是无法实现该功能,必须在脚本中指定该function,才能应用的!可是每个脚本中指定的话,不如放在 .bashrc中方便呀。

我把function定义单独写一个文件, 然后在script 里面 source 一下,是可以执行的!
但是,我现在是想在 .bashrc中就source,这样用户不是可以随时在每个script里面不必source 一下,就可以应用了吗!我看的书里面的例子就是那么设定的。我按书中的例子试了试,可以cli直接调用function,而在新建的脚本中不行。
请问是我的系统CentOS5问题,还是其他方面的问题!?书中的系统好像是 fedora! 和 SimplyMEPIS! 
望 指教!
发表于 2010-3-17 19:46:47 | 显示全部楼层
这种情况属于非交互 bash - 既执行脚本 (non-interactive, non-login) ,不执行 ~/.bashrc。

~/.bashrc 只在交互的非登陆 shell 启动时使用

http://imghch.com/doc/bk03ch02.html
回复 支持 反对

使用道具 举报

发表于 2010-3-20 08:53:52 | 显示全部楼层
duplicate post
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表