Linux中的位置变量和预定义变量


位置变量

脚本中$1-$9,表示第一个到第九个参数

编写脚本
vi location_var.sh

#!/bin/bash

echo $1
echo this is the $2
echo $6

修改文件为当前用户可执行
chmod u+x location_var.sh

执行脚本文件,参数之间必须用空格分割(可以是多个),因为每个参数之间用空格分割,所以shell会将空格当成两个值的分隔符,如果要在参数中包含空格,必须要用引号(单引号或双引号均可)
./location_var.sh canshu1 canshu2 chanshu3 canshu4 canshu5 canshu6 canshu7

执行结果为

canshu1
this is the canshu2
canshu6

执行以下命令
./location_var.sh canshu1 'canshu2 double'

执行结果为:

canshu1
this is the canshu2 double

说明:将文本字符串作为参数传递时,引号并非数据的一部分,它们只是表明数据的起止位置。因为没有输入参数6,所以第三行结果为空行

预定义变量

$0: 表示脚本的名称

执行以下脚本

bash test1.sh

#!/bin/bash

echo The parameter is set to: $0

结果为:

The parameter is set to: test1.sh

注意:如果使用另一个命令来运行shell脚本,命令会和脚本名混在一起,出现在$0参数中
例如:./test1.sh
结果为:

The parameter is set to: ./test1.sh

执行/opt/modules/hive-3.1.1/shell/test1.sh

结果为:

The parameter is set to: /opt/modules/hive-3.1.1/shell/test1.sh

如果你要编写一个根据脚本名来执行不同功能的脚本时,你还得把脚本的运行路径给剥离掉,另外,还要删除与脚本名混杂在一起的命令。

在shell中,有一个命令会返回不包含路径的脚本名:basename
cat test2.sh

#!/bin/bash

name=$(basename $0)  # shell中变量赋值=号两边不能有空格
echo
echo The script name is: $name

bash /opt/modules/hive-3.1.1/shell/test2.sh
结果为:


The script name is: test2.sh

./test2.sh
结果为:


The script name is: test2.sh

$#:统计参数的个数

cat test3.sh

#!/bin/bash

echo There were $# parameters supplied.

./test3.sh
结果为:

There were 5 parameters supplied.

这个变量还提供了一个简便方法来获取命令行中最后一个参数
cat test4.sh

#!/bin/bash

params=$#
echo
echo The last parameter is ${!#}
echo The parameter number is $params

./test4.sh 1 3 5 6 9 8 2
结果为:


The last parameter is 2
The parameter number is 7

注意:当命令行上没有任何参数时,$#的值为0,params变量的值也一样,但${1#}变量会返回命令行用到的脚本名
./test4.sh
结果为:


The last parameter is ./test4.sh
The parameter number is 0

$*:所有的参数,整体,$@: 表示所有参数,一个参数是一个整体

$*和$@变量可以用来访问所有参数,但又有区别:
$*变量会将命令行上提供的所有参数当做一个单词保存,这个单词包含了命令行中出现的每一个参数值,基本上$*变量会将这些参数视为一个整体,而不是多个个体。
$@变量会将命令行上提供的所有参数当做同一字符串中的多个独立单词,这样我们能够遍历所有的参数值,得到每个参数,这通常通过for命令完成。

cat test4.sh

#!/bin/bash

echo "Using the \$* method: $*"
echo
echo "Using the \$@ method: $@"

./test5.sh jack rose

结果为:

Using the $* method: jack rose

Using the $@ method: jack rose

从表面上看,两个变量产生的是同样的输出,都显示了所有命令行的参数。但实际不一样
cat test6.sh

#!/bin/bash

count=1
for param in "$*"
do
    echo "\$* Parameter #$count = $param"
    count=$[ $count + 1 ]
done

echo

count=1
for param in "$@"
do
    echo "\$@ Parameter #$count = $param"
    count=$[ $count + 1 ]
done

./test6.sh hive hbase spark scala java python kafka

结果为:

$* Parameter #1 = hive hbase spark scala java python kafka

$@ Parameter #1 = hive
$@ Parameter #2 = hbase
$@ Parameter #3 = spark
$@ Parameter #4 = scala
$@ Parameter #5 = java
$@ Parameter #6 = python
$@ Parameter #7 = kafka

$?:上一条命令执行的结果

0:上一条命令正确执行了
非0:上一条命令执行失败了
$ ls /etc/passwd
/etc/passwd

$ echo $?
0

 ls /etc/passwdd
ls: cannot access /etc/passwdd: No such file or directory

echo $?
2

$!: 表示进程PID

后续补充

猜你喜欢

转载自blog.csdn.net/lz6363/article/details/87954929