0 bash变量类型:
环境变量
本地变量(局部变量)
位置变量: $1, $2, ... 分别表示第一个参数,第二个参数....
特殊变量
$?: 上个命令执行结果状态码
$#:参数的个数
$*: 参数列表
$@:参数列表
1 变量赋值后引用:
${varname} 其中{}可以省略, 只要在使用时,不会引起混淆那么{}就可以省略
eg:
[root@h2sliver114 local]# name=zm
[root@h2sliver114 local]# echo "hello ${name}s." 此时建议加上{}
2 具体变量类型介绍:
本地变量:
set VARNAME=VALUE: 作用域为整个bash进程;
局部变量:
local VARNAME=VALUE:作用域为当前代码段;
环境变量:作用域为当前shell进程及其子进程;
export VARNAME “导出”
位置变量:
$1, $2, ...
特殊变量:
$?: 上一个命令的执行状态返回值;
程序执行,可能有两类返回值:
程序执行结果
程序状态返回代码(0-255)
0: 正确执行
1-255:错误执行,1,2,127系统预留;
3 查看当前shell中的环境变量:
printenv 这是习惯用到的
env
export
4 位置变量:
eg:
sh filetest.sh /etc/fstab /etc/inittab
$1: /etc/fstab
$2: /etc/inittab
5 shift使用:
shift 2 表示一次踢出去2个 获取踢出去的这两个中最后的那一个 默认是移动1个
使用案例:
#!/bin/sh
#
echo "the first param is: $1"
shift
echo "the second param is: $1"
shift
echo "the third param is: $1"
结果:
[root@chinadaas109 zhoumingtest]# sh fortest.sh 1 2 3
the first param is: 1
the second param is: 2
the third param is: 3
6 变量赋初始值:
${parameter:-word}:如果parameter为空或未定义,则变量展开为“word”;否则,展开为parameter的值; 所谓展开就是直接打印出结果
${parameter:+word}:如果parameter为空或未定义,不做任何操作;否则,则展开为“word”值;
${parameter:=word}:如果parameter为空或未定义,则变量展开为“word”,并将展开后的值赋值给parameter;
${parameter:offset} 获取从数组脚本offset开始到最后字符的数据
${parameter:offset:length}:取子串,从offset处的后一个字符开始(角标从0开始计数),取lenth长的子串;
使用案例:
[root@chinadaas11 ~]# a=${a:-2}
[root@chinadaas11 ~]# echo $a
2
[root@chinadaas11 ~]# echo ${a:=30}
30
[root@chinadaas11 ~]# echo $a
30
[root@chinadaas11 ~]# a='hello world'
[root@chinadaas11 ~]# echo ${a:1:4}
ello
[root@chinadaas11 ~]# echo ${a:1}
ello world
7 脚本读取配置文件
一般在如下目录下:
/etc/rc.d/init.d/服务脚本
服务脚本支持配置文件:/etc/sysconfig/服务脚本同名的配置文件
如何让脚本来使用配置文件:
[root@chinadaas11 zm]# ll
total 8
-rw-r--r-- 1 root root 10 Nov 2 14:48 a.conf
-rw-r--r-- 1 root root 60 Nov 2 14:54 test.sh
[root@chinadaas11 zm]# cat a.conf
name='zm'
[root@chinadaas11 zm]# cat test.sh
#!/bin/bash
#
. /root/zm/a.conf ---> 等效于 source /root/zm/a.conf 在当前bash环境下读取并执行文件中的命令
[ -n $name ] && echo $name
[root@chinadaas11 zm]# sh test.sh
zm