Sometimes another shell script (such as parameter_usage.sh) is called in a shell script (such as test_call_other_shell.sh). Here are several feasible methods, which are applicable to both linux and windows (via Git Bash) :
1 .By source: running in the same process, after calling parameter_usage.sh in test_call_other_shell.sh, the variables and functions in parameter_usage.sh can be used directly in test_call_other_shell.sh 2.By /bin/
bash: running in a different process
3. Through sh: running in different processes
4. Through .: running in the same process, after calling parameter_usage.sh in test_call_other_shell.sh, the variables and functions in parameter_usage.sh can be used directly in test_call_other_shell.sh
The content of parameter_usage.sh is as follows:
#! /bin/bash
# 参数的使用
# 我们可以在执行Shell脚本时,向脚本传递参数,脚本内获取参数的格式为:$n. n代表一个数字,1为执行脚本的第一个参数,2为执行脚本的第二个参数,以此类推
if [ $# != 3 ]; then
echo "usage: $0 param1 param2 param3"
echo "e.g: $0 1 2 3"
exit 1
fi
echo "执行文件名: $0"
echo "param1: $1"; echo "param2: $2"; echo "param3: $3"
parameters=$*
# 特殊字符用来处理参数
# $#: 传递到脚本的参数个数
echo "参数个数为: $#"
# $*: 以一个单字符串显示所有向脚本传递的参数
echo "传递的参数作为一个字符串显示: $*"
# $@: 与$*相同,但是使用时加引号,并在引号中返回每个参数
echo "传递的参数作为字符串显示: $@"
for i in "$*"; do # 循环一次
echo "loop"; echo $i
done
echo ""
for i in "$@"; do # 循环三次
echo "loop"; echo $i
done
get_csdn_addr()
{
echo "csdn addr: https://blog.csdn.net/fengbingchun/"
}
The content of test_call_other_shell.sh is as follows:
#! /bin/bash
params=(source /bin/bash sh .)
usage()
{
echo "Error: $0 needs to have an input parameter"
echo "supported input parameters:"
for param in ${params[@]}; do
echo " $0 ${param}"
done
exit -1
}
if [ $# != 1 ]; then
usage
fi
flag=0
for param in ${params[@]}; do
if [ $1 == ${param} ]; then
flag=1
break
fi
done
if [ ${flag} == 0 ]; then
echo "Error: parameter \"$1\" is not supported"
usage
exit -1
fi
echo "==== test $1 ===="
$1 parameter_usage.sh 1 2 3
echo "parameters: ${parameters}"
get_csdn_addr
$1 parameter_usage 123
#ret=$?
#if [[ ${ret} != 0 ]]; then
# echo "##### Error: some of the above commands have gone wrong, please check: ${ret}"
# exit ${ret}
#fi
if [ $? -ne 0 ]; then
echo "##### Error: some of the above commands have gone wrong, please check"
exit -1
fi
echo "test finish"
The execution results on linux are as follows:
The execution results on windows are as follows:
Under Linux, you can also add the path where another shell script is located to the $PATH environment variable, and then you can call it as a normal command.