Linux shell 位置变量详解
什么是位置变量?
简单来说,在用户运行脚本的同时输入参数,这些参数所对应的变量称为位置变量。
例子:
- [root@XiaoPeng scripts]# ./ping.sh www.baidu.com
- Host www.baidu.com is up.
- [root@XiaoPeng scripts]# ./ping.sh klsdjfkldjfkldf.kljjfdkljfdljds.com
- Host klsdjfkldjfkldf.kljjfdkljfdljds.com is down.
在调用脚本的时候赋值。
查看脚本:
- [root@XiaoPeng scripts]# cat ping.sh
- #!/bin/bash
- #arppinging or XiaoPeng
- ping -c 2 -w 2 $1 >/dev/null 2>&1
- [ $? -eq 0 ] && echo "Host $1 is up." || echo "Host $1 is down."
位置参数
$1:第一个参数,比如 ./ping.sh 1.1.1.1 2.2.2.2,那么$1就是1.1.1.1
$2:第二个参数,比如./ping.sh 1.1.1.1 2.2.2.2,那么$2就是2.2.2.2
......
$0:脚本名字
$#:一共有几个参数
$@:显示全部参数
例子:
- 查看脚本
- #!/bin/bash -
- #arppinging or XiaoPeng
- echo ' $0 $1 $2 $# $@'
- echo $0 $1 $2 $# $@
- **执行脚本**
- [root@XiaoPeng scripts]# ./var.sh 1 2 3 4 5
- $0 $1$2$# $@
- ./var.sh 1 2 5 1 2 3 4 5
总结:记住几个常用的参数$0\$1\$#\$@即可。
版权:arppinging