一、接收固定长度的参数
复制代码 代码如下:
[root@svn shell_example]# cat params.sh
#!/bin/bash
#传参测试脚本
echo "My name is `basename $0` -I was called as $0"
echo "My first parameter is : $1"
echo "My second parameter is : $2"
空参数执行
复制代码 代码如下:
[root@svn shell_example]# sh params.sh
My name is params.sh -I was called as params.sh
My first parameter is :
My second parameter is :
传递2个参数执行
复制代码 代码如下:
[root@svn shell_example]# sh params.sh one two
My name is params.sh -I was called as params.sh
My first parameter is : one
My second parameter is : two
二、那如果还有参数怎么办呢"codetitle">复制代码 代码如下:
[root@svn shell_example]# sh params_v2.sh
My name is params_v2.sh -I was called as params_v2.sh
I was called with 0 parameters.
Usage: params_v2.sh first second
You provided 0 parameters,but 2 are required.
代码如下
复制代码 代码如下:
[root@svn shell_example]# cat params_v2.sh
#!/bin/bash
# 这是个测试脚本传参的测试例子
echo "My name is `basename $0` -I was called as $0"
echo "I was called with $# parameters."
if [ "$#" -eq "2" ];then
echo "My first parameter is $1"
echo "My second parameter is $2"
else
echo "Usage: `basename $0` first second"
echo "You provided $# parameters,but 2 are required."
fi
详细的执行过程如下
不传参数执行
复制代码 代码如下:
[root@svn shell_example]# sh params_v2.sh
My name is params_v2.sh -I was called as params_v2.sh
I was called with 0 parameters.
Usage: params_v2.sh first second
You provided 0 parameters,but 2 are required.
传递3个参数执行
复制代码 代码如下:
[root@svn shell_example]# sh params_v2.sh one two three
My name is params_v2.sh -I was called as params_v2.sh
I was called with 3 parameters.
Usage: params_v2.sh first second
You provided 3 parameters,but 2 are required.
传递2个参数执行
复制代码 代码如下:
[root@svn shell_example]# sh params_v2.sh one two
My name is params_v2.sh -I was called as params_v2.sh
I was called with 2 parameters.
My first parameter is one
My second parameter is two
问题来了,要是后期还要加参数怎么办呢"codetitle">复制代码 代码如下:
[root@svn shell_example]# cat manyparams.sh
#!/bin/bash
#这是个测试脚本传N个参数的例子
echo "我的名字是 `basename $0` - 我是调用自 $0"
echo "我有 $# 参数"
count=1
while [ "$#" -ge "1" ];do
echo "参数序号为 $count 是 $1"
let count=count+1
shift
done
一个参数执行
[root@svn shell_example]# sh manyparams.sh one
我的名字是 manyparams.sh - 我是调用自 manyparams.sh
我有 1 参数
参数序号为 1 是 one
5个参数执行
复制代码 代码如下:
[root@svn shell_example]# sh manyparams.sh one two three four five
我的名字是 manyparams.sh - 我是调用自 manyparams.sh
我有 5 参数
参数序号为 1 是 one
参数序号为 2 是 two
参数序号为 3 是 three
参数序号为 4 是 four
参数序号为 5 是 five
Shell脚本,传参数
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]