[转载]Bourne Shell及shell编程 五
时间:2005-11-26 来源:ghostzhu
版权声明:
本文内容为大连理工大学LINUX选修课讲义,欢迎大家转载,但禁止使用本材料进行
任何商业性或赢利性活动。转载时请保留本版权声明。
作者:何斌武,[email protected],大连理工大学网络中心,April 1999.
[请点击阅读全文]
——by ghostzhu
<3> 混合命令条件执行
command1 && command2 && command3
当command1, command2成功时才执行command3
command1 && command2 || comamnd3
仅当command1成功,command2失败时才执行command3
当然可以根据自己的需要进行多种条件命令的组合,在此不多讲述。
(8) 使用getopts命令读取unix格式选项
UNIX格式选项指如下格式的命令行参数:
command -options parameters
使用格式:
getopts option_string variable
具体使用方法请参考getopts的在线文档(man getopts).
示例如下:
#newdate
if [ $# -lt 1 ]
then
date
else
while getopts mdyDHMSTjJwahr OPTION
do
case $OPTION
in
m) date +%m ;; # Month of Year
d) date +%d ;; # Day of Month
y) date +%y ;; # Year
D) date +%D ;; # MM/DD/YY
H) date +%H ;; # Hour
M) date +%M ;; # Minute
S) date +%S ;; # Second
T) date +%T ;; # HH:MM:SS
j) date +%j ;; # day of year
J) date +%y%j ;;# 5 digit Julian date
w) date +%w ;; # Day of the Week
a) date +%a ;; # Day abbreviation
h) date +%h ;; # Month abbreviation
r) date +%r ;; # AM-PM time
?) echo "Invalid option $OPTION";;
esac
done
fi
$ newdate -J
94031
$ newdate -a -h -d
Mon
Jan
31
$ newdate -ahd
Mon
Jan
31
$
示例程序:复制程序
# Syntax: duplicate [-c integer] [-v] filename
# where integer is the number of duplicate copies
# and -v is the verbose option
COPIES=1
VERBOSE=N
while getopts vc: OPTION
do
case $OPTION
in
c) COPIES=$OPTARG;;
v) VERBOSE=Y;;
?) echo "Illegal Option"
exit 1;;
esac
done
if [ $OPTIND -gt $# ]
then
echo "No file name specified"
exit 2
fi
shift `expr $OPTIND -1`
FILE=$1
COPY=0
while [ $COPIES -gt $COPY ]
do
COPY=`expr $COPY + 1`
cp $FILE ${FILE}${COPY}
if [ VERBOSE = Y ]
then
echo ${FILE}${COPY}
fi
done
$ duplicate -v fileA
fileA1
$ duplicate -c 3 -v fileB
fileB1
fileB2
fileB3
4. Shell的定制
通常使用shell的定制来控制用户自己的环境,比如改变shell的外观(提示符)以及增强
自己的命令。
(1)通常环境变量来定制shell
通常改变环境变量可以定制shell的工作环境。shell在处理信息时会参考这些环境变量
,改变环境变量的值在一定程度上改变shell的操作方式,比如改变命令行提示符。
.使用IFS增加命令行分隔符
默认状态下shell的分隔符为空格、制表符及换行符,但可以通过改变IFS的值加入自
己
的分隔符。如下所示:
$ IFS=":"
$ echo:Hello:my:Friend
Hello my Friend
(2)加入自己的命令及函数
如下程序:
#Directory and Prompt change program
#Syntax: chdir directory
if [ ! -d "$1" ]
then
echo "$1 is not a directory"
exit 1
fi
cd $1
PS1=`pwd`$
export PS1
$ chdir /usr/home/teresa
$
但此程序在执行时系统提示符并不会改变,因为此程序是在子shell中执行的。因此其
变
量
对当前shell并无影响,要想对当前shell起作用,最好是将此作为函数写在自己的.profi
le
中
或建立自己的个人函数文件.persfuncs
#Personal function file persfuncs
chdir()
{
#Directory and Prompt change program
#Syntax: chdir directory
if [ ! -d "$1" ]
then
echo "$1 is not a directory"
exit 1
fi
cd $1
PS1=`pwd`$
export PS1;
}
再执行:
$ . .persfuncs
$ chdir temp
/home/hbbwork/temp$
也可在自己的.profile文件中用 . .persfuncs调用.persfuncs.
说明:在bash/tcsh中已经使用别名,相对而言别名比此方法更为方便。