很多初学linux shell编程的朋友对命令行参数这块不熟悉,本节脚本小编就为大家带来linux shell命令行参数的用法实例教程,一起来看看吧。
shell命令行参数实例教程。
一、用户交互
1、命令行参数
$0:程序名
$1~$9:参数
当多余9个参数时: ${10} ${11}...${n}
2、参数个数:$#
3、最后一个参数:${!#} 或 last=$#;$last
4、全部参数
$*:把整行当成一个参数
$@:同一字符串中的多个对立单词
基本上使用$@
5、移动参数变量shift n(无n默认1)
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
while [ -n "$1" ]
do
echo $1
shift
done
exit 0
6、处理选项
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
while [ -n "$1" ]
do
case $1 in
-a) echo "-a option";;
-b) echo "-b option";;
-c) echo "-c option";;
*) echo $1" is not a option"
esac
shift
done
exit 0
7、getopt命令的使用
getopt abc:d -abd -c test1 test2
result: -a -b -d -c test1 -- test2
脚本中使用set -- `getopt -q abc:d "$@"`
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
set -- `getopt ab:c "$@"`
while [ -n "$1" ]
do
case $1 in
-a) echo "-a option";;
-b) echo "-b option -param "$2
shift;;
-c) echo "-c option";;
--) shift;
break;;
*) echo $1" is not a option"
esac
shift
done
for p in $@
do
echo "params $p"
done
exit 0
第二部分,getopts高级使用
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
while getopts :ab:c opt
do
case $opt in
a) echo '-a option';;
b) echo '-b option with param '$OPTARG;;
c) echo '-c option';;
*) echo 'unknown option '$opt
esac
done
shift $[ $OPTIND - 1 ]
for p in $@
do
echo "param: "$p
done
exit 0
8、用户输入
read -n -t -p var_input
read -s 密码输入等用到
$REPLY变量将存放输入的值