欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux学习之shell 编程基础(二)

程序员文章站 2022-06-24 20:31:39
...

一、bash环境变量

HOME、MAIL、SHELL、PATH 等,环境变量大都用大写字母组成

[[email protected] dalianmao]# echo $SHELL
/bin/bash
[[email protected] dalianmao]# echo $PATH
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/dalianmao/bin
[[email protected] dalianmao]# echo $MAIL
/var/spool/mail/dalianmao
[[email protected] dalianmao]# echo $HOME
/root

二、变量的取用与设定:echo,变量设定规则,unset

(1)echo $ variable

[[email protected] dalianmao]# echo $HOME
/root

(2)变量设定规则

  1、等号两边不能直接接空格符,如下所示为错误

[[email protected] dalianmao]# myname = dalianmao
bash: myname: command not found
[[email protected] dalianmao]# myname= dalianmao
bash: dalianmao: command not found

2、变量名称只能是英文字母与数字,但是开头字符不能是数字,如下为错误:

[[email protected] dalianmao]# 2myname=dalianmao
bash: 2myname=dalianmao: command not found

3、变量内容若有空格符可使用双引号或者单引号将变量内容结合起来,但

[[email protected] ~]$ name=dalianmao
[[email protected] ~]$ name='my name is $name'
[[email protected] ~]$ echo $name
my name is $name

4、可用跳脱字符  \ 将特殊符号(如Enter,$,\,空格符,' 等)变成一般字符;

5、在一串指令中,还需要籍由其他的指令提供的信息,可以使用反单引号` $

[[email protected] ~]$ clear
[[email protected] ~]$ myname=`ll|grep wzc`
[[email protected] ~]$ echo $myname
drwxr-xr-x. 3 root root 4096 Sep 21 09:13 wzc
[[email protected] ~]$ name=$(ll|grep wzc)
[[email protected] ~]$ echo $name
drwxr-xr-x. 3 root root 4096 Sep 21 09:13 wzc

6、若该变量为扩增内容时,则可用“$变量”或${变量}累加内容。

[[email protected] ~]$ myname=dalianmao
[[email protected] ~]$ echo $myname
dalianmao
[[email protected] ~]$ myname=${myname}' is my name!'
[[email protected] ~]$ echo $myname
dalianmao is my name!
[[email protected] ~]$ myname="$myname"' is myname!hahahhaha'
[[email protected] ~]$ echo $myname
dalianmao is my name! is myname!hahahhaha

7、若该变量需要在其他子程序执行,则需要以export来使变量变成环境变量。

[[email protected] ~]$ name=dalianmao
[[email protected] ~]$ echo $name
dalianmao
[[email protected] ~]$ bash
[[email protected] ~]$ echo $name

[[email protected] ~]$ exit
exit
[[email protected] ~]$ export name
[[email protected] ~]$ bash
[[email protected] ~]$ echo $name
dalianmao
[[email protected] ~]$ exit
exit
[[email protected] ~]$ unset name
[[email protected] ~]$ echo $name

[[email protected] ~]$ 

8、取消变量的方法为使用unset。

[[email protected] ~]$ myname=dalianmao
[[email protected] ~]$ echo $myname
dalianmao
[[email protected] ~]$ unset myname
[[email protected] ~]$ echo $myname

[[email protected] ~]$