我有一个脚本a.sh
,它有:
a() {
echo "123"
}
echo "dont"
然后我有另一个脚本b.sh
,它有:
b() {
echo "345"
}
我只想在b
中使用a
,但当我获取它时,我不想打印a()
或echo "Dont"
中的任何内容。
我现在只想找到它的来源。
所以我做了,在b.sh
中源a.sh
但它不起作用。
采购的原因是。所以如果我想要,我也可以在我想要的时候调用任何函数。
如果我在b.sh
中执行. /a.sh
,它会打印a.sh
中的所有内容。
在任何符合POSIX的shell上都可以使用的一种方法是:
# put function definitions at the top
a() {
echo "123"
}
# divide them with a conditional return
[ -n "$FUNCTIONS_ONLY" ] && return
# put direct code to execute below
echo "dont"
在你的另一个脚本中:
FUNCTIONS_ONLY=1 . other.sh
在名为functionLib.sh
的文件中创建一个公共函数库,如下所示:
#!/bin/sh
a(){
echo Inside a, with $1
}
b(){
echo Inside b, with $1
}
然后在script1
中,执行以下操作:
#!/bin/sh
. functionLib.sh # Source in the functions
a 42 # Use one
b 37 # Use another
在另一个脚本中,script2
重用函数:
#!/bin/sh
. functionLib.sh # Source in the functions
a 23 # Re-use one
b 24 # Re-use another
我在shell脚本中采用了一种风格,允许我将每个脚本设计为一个潜在的库,使其在来源(使用. .../path/script
)和直接执行时表现不同。您可以将其与python if __name__ == '__main__':
技巧进行比较。
我还没有发现一种方法可以在不明确引用脚本名称的情况下在所有Bourne shell子代中移植,但我使用的是:
a() {
echo a
}
b() {
echo b
}
(program=xyzzy
set -u -e
case $0 in
*${program}) : ;;
*) exit;;
esac
# main
a
b
)
这种方法的规则是严格的:
开始一个只有函数的部分。没有变量分配或任何其他活动。
然后,在最后创建一个子shell
(
。。。)
子外壳内的第一个操作测试它的来源。如果是,请退出潜艇外壳。如果没有,请运行命令。