Shell变量类型

来源:互联网 发布:cf免费刷火麒麟软件 编辑:程序博客网 时间:2024/06/07 07:30

Shell变量类型

Shell中变量的类型分为环境变量,位置变量,预定义的特殊变量以及用户自定义变量。

1.Shell环境变量

HOME:用户主目录的全路径名

chen@chen-IdeaPad-Y430:~$ echo $HOME
/home/chen

PATH:定义了一些目录路径,冒号分隔。在执行命令或Shell脚本时,Shell会按设定的顺序搜索这些目录。

chen@chen-IdeaPad-Y430:~$ echo $PATH
/home/chen/hadoop-1.2.1/bin:/home/chen/jdk1.7.0_60/bin:/home/chen/jdk1.7.0_60/jre/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

PWD:当前工作目录的绝对路径

LOGNAME:登录用户的用户名

UID:当前用户的UID

chen@chen-IdeaPad-Y430:~$ echo $UID

1000

2.位置变量

位置变量依据出现在命令行上的参数的位置来确定变量。

$命令 参数1 参数2 参数3

$0:对应当前执行的命令名

$1-$9:对应第1-9个位置参数

当命令行上的参数多于9个时,需要用shift命令移动位置参数,每执行一次shift命令,变量0不变,从1开始位置参数左移一位。

编写shifttest程序

echo $0 $1 $2 $3 $4 $5 $6 $7 $8 $9
shift
echo $0 $1 $2 $3 $4 $5 $6 $7 $8 $9
shift 2
echo $0 $1 $2 $3 $4 $5 $6 $7 $8 $9

执行如下

chen@chen-IdeaPad-Y430:~$ chmod u+x shifttest 
chen@chen-IdeaPad-Y430:~$ ./shifttest  a b c d e f g h j

./shifttest a b c d e f g h j
./shifttest b c d e f g h j
./shifttest d e f g h j

whileshift程序如下

#!/bin/bash
#filename:whileshift
echo "----start----"
 while [ $# -gt 0 ]


 do
  echo "position: $* "
shift
 done
echo "---end---"

执行如下

chen@chen-IdeaPad-Y430:~$ .chmod u+x whileshift

chen@chen-IdeaPad-Y430:~$ ./whileshift  11 22 33 44 55 66 77
----start----
position: 11 22 33 44 55 66 77 
position: 22 33 44 55 66 77 
position: 33 44 55 66 77 
position: 44 55 66 77 
position: 55 66 77 
position: 66 77 
position: 77 
---end---

3.预定义的特殊变量

$#: 实际位置参数个数

$*:命令行中所有位置参数组成的字符串

$!:上一个后台命令对应的进程号

$?:最近一条命令执行后的退出状态

$$:当前进程号PID

编写myprt程序

chen@chen-IdeaPad-Y430:~$ cat myprg 
echo "参数个数: $#"
echo "参数: $* "
echo "前三个: $1 $2 $3 "
echo "最后一个参数: $4 "

执行如下

chen@chen-IdeaPad-Y430:~$ chmod u+x myprg 
chen@chen-IdeaPad-Y430:~$ ./myprg A B C D
参数个数: 4
参数: A B C D 
前三个: A B C 
最后一个参数: D 

对指定目录进行备份的程序

chen@chen-IdeaPad-Y430:~$ cat lastresult 
#!/bin/bash
#filename: lastresult
if [ $# -eq 1 ];then
 DIR=$1
 FILE= `basename $0 `
 DIR2= `basename $1 `
 if [ -x $DIR ];then
  tar zcvf ${FILE}${DIR2}.tar.gz $DIR
 else
  echo " $DIR is not exist, please try again! "
 fi
else
 echo " please enter an argument. "
fi

执行后在当前目录生成一个.tar.gz文件

4.用户自定义的变量

变量区分大小写,由字母或下划线开头,后面是任意数量的字母,数字,下划线。






















0 0
原创粉丝点击