当前位置: 首页 > news >正文

shell脚本内调用另外一个shell脚本的几种方法

      有时会在一个shell脚本(如test_call_other_shell.sh)中调用另外一个shell脚本(如parameter_usage.sh),这里总结几种可行的方法,这些方法在linux上和windows上(通过Git Bash)均适用
      1.通过source: 运行在相同的进程,在test_call_other_shell.sh中调用parameter_usage.sh后,parameter_usage.sh中的变量和函数在test_call_other_shell.sh中可直接使用
      2.通过/bin/bash: 运行在不同的进程
      3.通过sh: 运行在不同的进程
      4.通过.: 运行在相同的进程,在test_call_other_shell.sh中调用parameter_usage.sh后,parameter_usage.sh中的变量和函数在test_call_other_shell.sh中可直接使用

      parameter_usage.sh内容如下:

#! /bin/bash# 参数的使用# 我们可以在执行Shell脚本时,向脚本传递参数,脚本内获取参数的格式为:$n. n代表一个数字,1为执行脚本的第一个参数,2为执行脚本的第二个参数,以此类推if [ $# != 3 ]; thenecho "usage: $0 param1 param2 param3"echo "e.g: $0 1 2 3"exit 1
fiecho "执行文件名: $0"
echo "param1: $1"; echo "param2: $2"; echo "param3: $3"parameters=$*# 特殊字符用来处理参数
# $#: 传递到脚本的参数个数
echo "参数个数为: $#"
# $*: 以一个单字符串显示所有向脚本传递的参数
echo "传递的参数作为一个字符串显示: $*"
# $@: 与$*相同,但是使用时加引号,并在引号中返回每个参数
echo "传递的参数作为字符串显示: $@"for i in "$*"; do # 循环一次echo "loop"; echo $i
doneecho ""
for i in "$@"; do # 循环三次echo "loop"; echo $i
doneget_csdn_addr()
{echo "csdn addr: https://blog.csdn.net/fengbingchun/"
}

      test_call_other_shell.sh内容如下:

#! /bin/bashparams=(source /bin/bash sh .)usage()
{echo "Error: $0 needs to have an input parameter"echo "supported input parameters:"for param in ${params[@]}; doecho "  $0 ${param}"doneexit -1
}if [ $# != 1 ]; thenusage
fiflag=0
for param in ${params[@]}; doif [ $1 == ${param} ]; thenflag=1breakfi
doneif [ ${flag} == 0 ]; thenecho "Error: parameter \"$1\" is not supported"usageexit -1
fiecho "==== 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 ]; thenecho "##### Error: some of the above commands have gone wrong, please check"exit -1
fiecho "test finish"

      在linux上的执行结果如下:

      在windows上执行结果如下:

      在linux下也可以将另外一个shell脚本所在的路径添加到$PATH环境变量,然后你就可以把它作为普通命令调用。

      GitHub: https://github.com/fengbingchun/Linux_Code_Test

http://www.lryc.cn/news/12511.html

相关文章:

  • Linux C++ 多进程下write写日志问题思考
  • MySQL的四种事务隔离级别
  • 方法区和元空间有什么关系?
  • 2023VNCTF的两道(暂时)
  • JDK版本区别
  • Android 基础知识4-2.8 TableLayout(表格布局)详解
  • SQL代码编码原则和规范
  • 【博客627】gobgp服务无损变更:graceful restart特性
  • 一起学 pixijs(1):常见图形的绘制
  • 2023年PMP考试教材有哪些?(含pmp资料)
  • centos7防火墙工具firewall-cmd使用
  • js html过滤所有标签格式并清除所有nbsp;
  • 「技术选型」深度学习软件如何选择?
  • 加油站会员管理小程序实战开发教程13
  • Go语言Web入门之浅谈Gin框架
  • 《MySQL学习》 MySQL优化器选择如何选择索引
  • uniapp 悬浮窗(应用内、无需授权) Ba-FloatWindow2
  • MMKV与mmap:全方位解析
  • 【信息系统项目管理师】项目管理十大知识领域记忆敲出(整体范围进度)
  • 一起学 pixijs(3):Sprite
  • 深入讲解Kubernetes架构-垃圾收集
  • Flink03: 集群安装部署
  • OCR项目实战(一):手写汉语拼音识别(Pytorch版)
  • 【js】export default也在影响项目性能呢
  • 《软件安全》 彭国军 阅读总结
  • 深入讲解Kubernetes架构-节点与控制面之间的通信
  • 120个IT冷知识,看完就不愁做选择题了
  • Java之动态规划之机器人移动
  • seata源码-全局事务提交 服务端源码
  • C++ 模板