向bash shell脚本传参

例子:

powershell 复制代码
~ script % touch parameter.sh
~ script % chmod 755 parameter.sh
~ % vim parameter.sh

parameter.sh:

powershell 复制代码
#!/usr/bin/env bash

echo the name of current script is $0

echo the first parameter is $1

echo the second parameter is $2

echo all parameters: $@

exit 0 

执行:

powershell 复制代码
script % ./parameter.sh a b
the name of current script is ./parameter.sh
the first parameter is a
the second parameter is b
all parameters: a b
  • $0 带全路径的脚本名称
  • $1 第1个参数
  • $2 第2个参数
  • $3 第3个参数
    ...
  • ${10} 第10个参数
    ...
  • ${255} 第255个参数
    最多可以有255个参数
  • @: 获取所有参数,除了脚本名称,即@等于1\~255的参数的集合

我们可以通过查询$?了解脚本程序退出的状态。因为上面的脚本加了exit 0表示退出时的状态是0,一般来说,当程序出现异常导致退出时,状态值是个非0的整数。 如果我们加上这一句exit 10,执行完脚本后,再查询一个退出状态,就会得到10,查询的方式:

powershell 复制代码
~ script % echo $?
10
相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
未济3 天前
linux 配置环境变量
linux
傲世仙尊3 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
_艾伦 耶格尔.4 天前
进程间通信
linux
Liuqy-054 天前
Linux IO编程——静态库、动态库
linux
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
孙启超4 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust