(6)shell环境变量
CDPATH 用于cd命令的查找路径
HOME /etc/passwd文件中列出的用户主目录
IFS Internal Field Separator,默认为空格,tab及换行符
MAIL /var/mail/$USERNAME mail等程序使用
PATH
PS1,PS2 默认提示符($)及换行提示符(>)
TERM 终端类型,常用的有vt100,ansi,vt200,xterm等
例:
$ str1=abcd #在含有空格时必须用引号括起来
$ test $str1=abcd
$ echo $?
0
$ str1="abcd "
$ test $str1=abcd
$ echo $?
1
Note: 在test处理含有空格的变量时最好用引号将变量括起来,否则会出现错误的
结果,
因为shell在处理命令行时将会去掉多余的空格,而用引号括起来则可以防止
shell去掉这些空格.
例:
$ str1=" "
$ test $str1
$ echo $?
1
$ test "$str1"
$ echo $?
0
$ test -n $str1
test: argument expected
$ test -n "$str1"
$ echo $?
0
$
b. 整数测试: test与expr相同,可以将字符型变量转换为整数进行操作,expr进行
整数的算术运算,而test则进行逻辑运算.
表达式 说明
---------------------------------------
int1 -eq int2 相等?
int1 -ne int2 不等?
int1 -gt int2 int1 > int2 ?
int1 -ge int2 int1 >= int2 ?
int1 -lt int2 int1 empty
$ test -r empty
$ echo $?
0
$ test -s empty
1
$ test ! -s empty
$ echo $?
0
e. 测试条件之逻辑运算
-a And
-o Or
例: $ test -r empty -a -s empty
$ echo $?
1
f. 进行test测试的标准方法
因为test命令在 shell编程中占有很重要的地位,为了使shell能同其他编程语言
一样
便于阅读和组织, Bourne Shell在使用test测试时使用了另一种方法:用方括号将
整个
test测试括起来:
$ int1=4
$ [ $int1 -gt 2 ]
$ echo $?
0
例: 重写unload程序,使用test测试
#!/bin/sh
#unload - program to backup and remove files
#syntax: unload directory
#check arguments
if [ $# -ne 1 ]
then
echo "usage: $0 directory"
exit 1
fi
#check for valid directory name
if [ ! -d "$1" ]
then
echo "$1 is not a directory"
exit 2
fi
cd $1
ls -a | cpio -o > /dev/rmt/0h
if [ $? -eq 0 ]
then
rm -rf *
else
echo "A problem has occured in creating backup"
echo "The directory will not be ereased"
echo "Please check the backup device"
exit 3
fi
# end of unload
until [ $# -eq 0 ]
do
echo "Argument is $1 and `expr $# - 1` argument(s) remain"
shift
done
$ shifter 1 2 3 4
Argument is 1 and 3 argument(s) remain
Argument is 2 and 2 argument(s) remain
Argument is 3 and 1 argument(s) remain
Argument is 4 and 0 argument(s) remain
$
#!/bin/sh
# Interactive program to restore, backup, or unload
# a directory
echo "Welcome to the menu driven Archive program"
while true
do
# Display a Menu
echo
echo "Make a Choice from the Menu below"
echo _
echo "1 Restore Archive"
echo "2 Backup directory"
echo "3 Unload directory"
echo "4 Quit"
echo
# Read the user's selection
echo -n "Enter Choice: "
read CHOICE
case $CHOICE in
[1-3] ) echo
# Read and validate the name of the directory
echo -n "What directory do you want? "
read WORKDIR
if [ ! -d "$WORKDIR" ]
then
echo "Sorry, $WORKDIR is not a directory"
continue
fi
# Make the directory the current working directory
cd $WORKDIR;;
4) :;; # :为空语句,不执行任何动作
*) echo "Sorry, $CHOICE is not a valid choice"
continue
esac
case "$CHOICE" in
1) echo "Restoring..."
cpio -i /dev/rmt/0h;;
3) echo "Unloading..."
ls | cpio -o >/dev/rmt/0h;;
4) echo "Quitting"
break;;
esac
#Check for cpio errors
if [ $? -ne 0 ]
then
echo "A problem has occurred during the process"
if [ $CHOICE = 3 ]
then
echo "The directory will not be erased"
fi
echo "Please check the device and try again"
continue
else
if [ $CHOICE = 3 ]
then
rm *
fi
fi
done