shell-的特殊变量-位置变量$0 $n $* $# $@详解

一:shell特殊变量
  1. 位置变量

$0      获取当前执行的shell脚本的文件名,包括路径
$n      获取当前执行的shell脚本的第n个参数值,n=1..9,当n为0时表示脚本的文件名,如果n大于9,用大括号括起来${10}
$*       获取当前shell的所有参数,将所有的命令行参数视为单个字符串,相当于"$1$2$3"........注意与$#的区别
$#       获取当前shell命令行中的参数的总个数
$@    这个程序的所有参数"$1" "$2"  "$3"  ".....",这是将参数传递给其他程序的最佳方式,因为他会保留所有内嵌在每个参数里的任何空白。
提示:$*和$@的区别?

 2.案例、演示

范例1:演示$0
[root@1-241 scripts]# cat 0.sh echo $0 [root@1-241 scripts]# sh 0.sh 0.sh [root@1-241 scripts]# cd /root/ [root@1-241 ~]# sh /scripts/0.sh /scripts/0.sh 范例2:演示$1到$10的作用 [root@1-241 scripts]# cat n.sh echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} [root@1-241 scripts]# sh n.sh `seq 10` 1 2 3 4 5 6 7 8 9 10 [root@1-241 scripts]# sh n.sh `seq 8` 1 2 3 4 5 6 7 8 [root@1-241 scripts]# sh n.sh `seq 12` 1 2 3 4 5 6 7 8 9 10 提示: 在脚本里写入$1到$10,在脚本执行传参,传入最大是10个参数,超过10个参数也不接收 范例3:演示$#的作用 [root@1-241 scripts]# cat n.sh echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} echo $# [root@1-241 scripts]# sh n.sh 1 2 3 4 5 1 2 3 4 5 5 提示 $#,显示传入了多少个参数

  

原文地址:https://www.cnblogs.com/scajy/p/12762281.html