Types of variables for bash
本地变量(局部变量)环境变量位置变量:$1,$2,$3, ...特殊变量:$?,$#,$*,[email protected]
The location variable that gives the script the ability to get external parameters,$1 for the first argument,$2 for the second argument, and so on
Cases:
vartest.sh
#!/bin/bash#ONEVAR=$1TWOVAR=$2THREEVAR=$3echo"第一个参数是:${ONEVAR}"echo"第二个参数是:${TWOVAR}"echo"第三个参数是:${THREEVAR}"
Results:
[root@iZ28g26851kZ ~]# ./vartest.sh /etc/passwd /etc/inittab /etc/rc.d/第一个参数是:/etc/passwd第二个参数是:/etc/inittab第三个参数是:/etc/rc.d/[root@iZ28g26851kZ ~]#
Here's another example of whether a file exists
filetest.sh
#!/bin/bash#FILENAME=$1if-e$FILENAME ];then echo"文件存在"else echo"文件不存在"fi
Results
[root@iZ28g26851kZ ~]# ./filetest.sh /etc/passwd文件存在[root@iZ28g26851kZ ~]# ./filetest.sh /etc/passwdasdas文件不存在[root@iZ28g26851kZ ~]#
is not very convenient,,
What happens if we don't take the parameters,
[root@iZ28g26851kZ ~]# ./filetest.sh文件存在[root@iZ28g26851kZ ~]#
Oh, this is very embarrassing ~ ~
If you can get the number of parameters passed in, it's OK,
It's going to introduce 特殊变量
$?:获取上一条命令执行的状态 --这个之前有讲过$#:获取脚本传进来的参数的个数 --haha,要的就是这个,有木有$*:显示参数的列表[email protected]:显示参数的列表
Okay, look again.
Filetest.sh
#!/bin/bash # if [$# -lt 1 ]; then echo "Usage:filetest.sh ARG" exit 6 fi Filename=$1 if [ -e $FILENAME ]; then echo "file exists" else echo "file does not exist" fi
Results
[root@iZ28g26851kZ ~]# ./filetest.shUsage:filetestARG[root@iZ28g26851kZ ~]# ./filetest.sh /etc/passwdasdas文件不存在[root@iZ28g26851kZ ~]# ./filetest.sh /etc/passwd文件存在[root@iZ28g26851kZ ~]#
OK, that's it.
So the question comes again, if there are 100 parameters, do I have to $1,$2,$3,$4, .... So it's going to be written dead,
So introduce one more command shift
Shift
Use the shift command in the script to "kick out" the first argument, and let the second parameter program the first parameter so that we can reference all the variables with $1.
shifttest.sh
#!/bin/bash#echo$1shiftecho$1shiftecho$1
Results:
[root@iZ28g26851kZ ~]# ./shifttest.sh asd fsdf 654asdfsdf654[root@iZ28g26851kZ ~]#
This allows you to remove the parameters in turn
Shell Programming for Linux Basics (3)-setting parameters for scripts