【shell】Linux shell 位置变量详解

前端之家收集整理的这篇文章主要介绍了【shell】Linux shell 位置变量详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Linux shell 位置变量详解

什么是位置变量?

简单来说,在用户运行脚本的同时输入参数,这些参数所对应的变量称为位置变量。

例子:

  1. [root@XiaoPeng scripts]# ./ping.sh www.baidu.com
  2. Host www.baidu.com is up.
  3. [root@XiaoPeng scripts]# ./ping.sh klsdjfkldjfkldf.kljjfdkljfdljds.com
  4. Host klsdjfkldjfkldf.kljjfdkljfdljds.com is down.

调用脚本的时候赋值。

查看脚本:

  1. [root@XiaoPeng scripts]# cat ping.sh
  2. #!/bin/bash
  3. #arppinging or XiaoPeng
  4. ping -c 2 -w 2 $1 >/dev/null 2>&1
  5.  
  6. [ $? -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:脚本名字
$#:一共有几个参数
$@:显示全部参数

例子:

  1. 查看脚本
  2. #!/bin/bash -
  3. #arppinging or XiaoPeng
  4.  
  5. echo ' $0 $1 $2 $# $@'
  6. echo $0 $1 $2 $# $@
  7.  
  8. **执行脚本**
  9. [root@XiaoPeng scripts]# ./var.sh 1 2 3 4 5
  10. $0 $1$2$# $@
  11. ./var.sh 1 2 5 1 2 3 4 5

总结:记住几个常用的参数$0\$1\$#\$@即可。

版权:arppinging

猜你在找的Bash相关文章