要传递命令行参数,我们只需在用空格分隔的脚本名之后编写它们。所有命令行参数都可以使用$来访问其位置编号。向shell脚本传递命令行参数的示例。
# sh myscript.sh 10 red admin.net
sh:linux shell
myscript.sh:linux shell 脚本
10:$1可访问的第一个命令行参数
red:第二个命令行参数,可以通过$2访问
admin.net:$3可访问的第三个命令行参数
访问带位置编号的命令行参数
如上所示,命令行参数可以在$1、$2、$3...$9、$10…$100等处访问。命令行参数的最大长度不是由shell定义的,而是由操作系统定义的,以千字节为单位。
$*:存储所有命令行参数
$@:存储所有命令行参数
$:存储命令行参数的计数
$0:脚本本身的存储名称
$1:存储第一个命令行参数
$2:存储第二个命令行参数
$3:存储第三个命令行参数
…
$9:存储第9个命令行参数
$10:存储第10个命令行参数
…
$99:存储第99个命令行参数
例1:
使用脚本名称和传递的参数总数创建一个shell脚本来打印所有参数。创建脚本文件myscript.sh要求以下内容。
#vim myscript.sh
#!/bin/bashecho script name: "$0"echo total number of argument passed: "$#"echo arguments list -echo 1. $1echo 2. $2echo 3. $3echo all arguments are: "$*"
执行脚本
# sh myscript.sh 10 rahul tecadmin.netscript name: myscrit.shtotal number of argument passed: 3arguments list -1. 102. red3. admin.netall arguments are: 10 red admin.net
例2:
通过shell脚本中的所有参数创建循环。为此,请创建一个shell脚本文件myscript2.sh,其中包含以下内容。
# vim myscript2.sh
#!/bin/bashfor i in "$@"do echo argument: $idone
执行脚本
# ./myscript2.sh 10 rahul tecadmin.netargument: 10argument: redargument: admin.net
通过移位来访问命令行参数
我们还可以通过改变命令行参数在shell脚本中的位置来访问它们。比如用$1访问第一个命令行参数。现在将参数换成1.意味着第二个参数现在位于第一个位置,相同的第三个位于第二个位置,依此类推。
使用下面的内容创建shell脚本myscript3.sh,并使用参数执行。现在现在观察如何在shell脚本中使用“shift <number>”命令移动参数。
#!/bin/bashecho first argument is: $1echo " >> shifting argument position by 1"shift 1echo now first argument is: $1echo " >> now shifting position with 2"shift 2echo now first argument is: $1echo " >> now shifting position with 4"shift 4echo now first argument is: $1
执行脚本并密切观察脚本中$1的输出。
[root@tecadmin ~]# sh myscrit3.sh a friend in need is a friend indeedfirst argument is: a >> shifting argument position by 1now first argument is: friend >> now shifting position with 2now first argument is: need >> now shifting position with 4now first argument is: indeed
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注的linux教程视频栏目!
以上就是如何在shell脚本中传递命令行参数的详细内容。
