shell是解释型语言
不象用C++/JAVA语言编程,不需要事先声明变量.
用户可以使用同一个变量,"时而"存放字符,"时而"存放整数.
字符串变量赋值很简单
logfile="/Users/mark/GPS.txt"
给变量赋值的注意事项
abc=9 (bash/pdksh,不能在等号两侧留下空格 )
set abc = 9 (csh /tcsh,正相反,必须在两侧留下空格)
字符串变量赋值,其值一般都用引号
但也可以不用引号(前提是字符串不成句,不能有空格)
name=hello echo $name [root@mac-home macg]# ./re.test hello |
name=hello world 错,不允许有空格 echo $name [root@mac-home macg]#./re.test ./re.test: line 2: world: command not found |
name="hello world" 有空格,就必须用双引号 echo $name [root@mac-home macg]# ./re.test hello world |
shell变量名中,不能有“中杠-",中杠会被识别为减号,必须改成"下杠_"
LAN-INT="eth0" /sbin/iptables -A INPUT -i $LAN-INT -j ACCEPT 系统提示不认识LAN-INT=eth0 原因:中杠会被识别为减号 |
解决:改成下杠就好了 LAN_INT="eth0" /sbin/iptables -A INPUT -i $LAN_INT -j ACCEPT |
变量引用
普通UNIX命令引用变量,要带$ sec=/home/macg cd $sec echo $r1 |
echo 双引号内引用变量,也要带$ echo "file $old is now called $new /c" |
变量也可直接执行,即变量值必须是一个命令字符串 ltest="ls -l" $ltest |
(read和赋值=和export,引用变量,不带$) new="test" read old export PATH |
字符串变量在if条件里,最好用" "引起来
read timeofday if [ $timeofday = “yes” ] |
如果read输入的仅是回车,if语句看起来就是下面的样子: if [ = “yes” ] 我们就会得到下面的错误信息: [: =: unary operator expected |
为了避免这样的问题,我们可以用双引号将变量括起来 当传递一个空串进行测试时: if [ “$timeofday” = “yes” ] if [ “” = “yes” ] 走else |
类似单引号,反斜线"/" 也能屏蔽所有特殊字符.但一次只能屏蔽一个字符.
echo "/$1 is $1" echo "this is $2" # sh ttt $1 is aa this is bb |
#echo “/$HOME = $PATH” # sh ttt $HOME = /bin:/etc:/usr/bin |
"" 引号中间没有任何字符,表示回车
$ vi ttt.sh echo -n "input:" read tt if [ "$tt" = "" ] 如果等于回车,则 then echo haha fi |
$ sh ttt.sh input: 此处回车 haha $ sh ttt.sh input:x |
$ cat in.sh while true do echo -n "input:" read msg if [ "$msg" = "" ] then continue else echo "your input is $msg" fi |
$ sh in.sh input:3 your input is 3 input:4 your input is 4 input: 回车走continue input: input: |
local 变量 ——只支持函数内变量定义
test() { local i for i in $* ; do echo "i is $i" done } |
test.sh: line 10: local: can only be used in a function |
删除变量unset,一般放在script结尾,释放空间
name="hello world"
echo $name
unset name
养成良好的习惯,在shell程序结束,就unset 变量和函数
pathmunge () {
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
fi
}
for i in /etc/profile.d/*.sh ; do
if [ -r "$i" ]; then
. $i
fi
done
unset i
unset pathmunge