|
小的纯属业余学习(未入门),还请各位大侠 详细解释!谢谢!!
.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!
望 指教! |
|