博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
shell 带参数脚本
阅读量:2431 次
发布时间:2019-05-10

本文共 1527 字,大约阅读时间需要 5 分钟。

本文编辑自:
当我们我们向
脚本文件传递参数
可以通过
$1,$2
等特殊变量。很方便,但是有些限制,就是不能超过9个参数。通过使用
shift
,我们可以向脚本文件传递更多的参数,通过
getopts
我们能更方便地提取参数。
一、shift
通过使用
shift
,我们将
shell脚本文件
的参数起点从左向右移。
在shift命令中可以给一个参数,以表示对shell脚本文件的传入参数启动从左向右移动多少。不给参数的话,表示移动一位。
实例1
test.sh文件
#!/bin/sh
# shift_sample
if 
$#
 -lt 1 ];then
echo "too few params"
exit 1
fi

while
 [ 
$#
 -ne 0 ]
do
echo $1
shift
done
在命令行下输入:
sh test.sh a b c
输出结果如下:
a
b
c
注意:“
$#”表示shell脚本文件传入参数的个数。

二、getopts
如果你的脚本命令后有一些选项开关,比如
-i
-c
等等,这个时候使用shift来挨个查看比较麻烦。而用getopts则比较方便。getopts使用格式如下:
getopts format_string variable
实例2
test.sh文件
#getopts_sample
if [ 
$# -lt 1
 ];then
echo "too few params"
exit 1
fi

while
 getopts hv OPTION
do
case
 
$OPTION
 in
h)
echo "this is help information"
shift
;;
v)
echo "the version is 1.0.0"
shift
;;
--)echo the option is end
shift
;;
esac
done
echo $1
这段脚本允许两个参数选项,分别是-h,-v,使用的时候可以分开来写,像-h -v,也可以连在一起,像-hv
运行命令“
sh test.sh -h -v Hello
”或
sh test.sh -hv Hello
,你将得到如下结果:
this is help information
the version is 1.0.0
hello
如果选项需要输入值,则在参数选项后面加上“
:
”,比如:getopts hvc: OPTION脚本在读到-c的时候,会把它的参数值存储在$OPTARG变量中。
实例3
test.sh文件
#!/bin/sh
#getopts_sample
if [ 
$# -lt 1
 ];then
echo "too few params"
exit 1
fi

while 
getopts hv:t: OPTION
do
case
 
$OPTION
 
in
h)
echo "this is option h"
shift 1
;;
v)
echo "this is option v.And the var is " $OPTARG
shift 2
;;
t)
echo "this is option t.And the var is " $OPTARG
shift 2
;;
esac
done
echo $1
运行命令“
sh test.sh -h -v vv -t tt hello
”将得到如下结果:
this is option h
this is option v.And the var is  vv
this is option t.And the var is  tt
hello

转载地址:http://tgtmb.baihongyu.com/

你可能感兴趣的文章
Python练手项目
查看>>
知网毕业论文爬取
查看>>
Django无法显示图片
查看>>
AOP技术基础
查看>>
聊聊Spring中的数据绑定 --- DataBinder本尊(源码分析)
查看>>
Spring MVC 框架的请求处理流程及体系结构
查看>>
mybatis-generator-gui界面工具生成实体
查看>>
Github访问速度很慢的原因,以及解决方法
查看>>
数据库分区、分表、分库、分片
查看>>
数据库垂直拆分 水平拆分
查看>>
关系型数据库设计:三大范式的通俗理解
查看>>
Hibernate常见面试题
查看>>
如何写一份优秀的java程序员简历
查看>>
如何避免软件行业的薪资天花板?
查看>>
Java知识体系最强总结(2020版)
查看>>
MyBatis与Hibernate区别
查看>>
笔记︱风控分类模型种类(决策、排序)比较与模型评估体系(ROC/gini/KS/lift)
查看>>
MySQL存储引擎之MyISAM与InnoDB区别
查看>>
Python numpy小练习
查看>>
Linux命令英文解释(按英文字母顺序)
查看>>