现在的位置: 首页 > 综合 > 正文

Linux 学习笔记_10_Shell编程_2_Shell编程语法(二)

2014年07月22日 ⁄ 综合 ⁄ 共 1817字 ⁄ 字号 评论关闭

变量测试语句

作用:用来测试变量是否相等,是否为空,文件类型等。
格式:
test 测试条件
范围:整数,字符串,文件
 
(1)整数测试: 
test int1 -eq int2
测试整数是否相等 
test int1 -ge int2
测试int1是否>=int2 
test int1 -gt int2
测试int1是否>int2 
test int1 -le
int2 测试int1是否<=int2 
test int1 -lt int2
测试int1是否<int2 
test int1 -ne int2
测试整数是否不相等
(2)字符串测试: 
test str1=str2
测试字符串是否相等 
test str1!=str2
测试字符串是否不相等 
test str1 测试字符串是否不为空 
test -n str1 测试字符串是否不为空 
test -z str1 测试字符串是否为空
(3)文件测试: 
test -d file 指定文件是否目录 
test -f file 指定文件是否常规文件 
test -x file 指定文件是否可执行 
test -r file 指定文件是否可读 
test -w file 指定文件是否可写 
test -a file 指定文件是否存在 
test -s file 文件的大小是否非0 

流程控制语句

流控制语句:用于控制shell程序的流程 
exit语句:退出程序执行,并返回一个返回码,返回码为0表示正常退出,非0表示非正常退出。 
例如:exit 0 

一、if/else
变量测试语句一般不单独使用,一般做为if语句的测试条件,如: 
if test -d $1 
then 
... 
fi 
变量测试语句可用[]进行简化,如test -d $1 等价于 [ -d $1 ] 
【实例】
#!/bin/sh 
if [ $# -ne 2 ]; then 
echo "Not enough parameters" 
exit 0 
fi 
if [ $1 -eq $2 ]; then 
echo "$1 equals $2" 
elif [ $1 -lt $2 ]; then 
echo "$1 littler than $2" 
elif [ $1 -gt $2 ]; then 
echo "$1 greater than $2" 
fi 

更复杂的if语句: 
if 条件1 
then 
命令1 
elif 条件2
then 
命令2 
else 
命令3 
fi 

多个条件的联合: 
-a: 逻辑与,仅当两个条件都成立时,结果为真。 
-o: 逻辑或,两个条件只要有一个成立,结果为真。

【示例】
#!/bin/bash
echo "please input a file name:" 
read file_name 
if [ -d $file_name ] 
then 
echo "$file_name is a directory" 
elif [ -f $file_name ] 
then 
echo "$file_name is a common file" 
elif [ -c $file_name -o -b $file_name ] 
then 
echo "$file_name is a device file“ 
else 
echo "$file_name is an unknown file" 
fi 

二、for/in
格式: for 变量 in 名字表 
do 
命令列表 
done 
【示例】
#!/bin/sh 
for DAY in Sunday Monday Tuesday Wednesday Thursday Friday Saturday 
do 
echo "The day is : $DAY" 
done 

【awk命令应用:分段提取】
awk -F域分隔符 ‘命令’【此处为单引号】 
【如果不用-F指定分割符,默认为空格】
1、检测系统中UID为0的用户 
awk -F: '$3==0 {print $1}' /etc/passwd 
-F: 指定分割附为:
$3 表示以:为分割附的第三位
2、检测系统中密码为空的用户 
awk -F: 'length($2)==0 {print $1}' /etc/shadow 

【重要实例】
#!/bin/bash 
  # A test shell for for and awk 
  username=$1 
  #提取所有username的pid 
  /bin/ps aux | /bin/grep $username | /bin/awk '{ print $2 }' > /home/xiaofang/test/tmp.txt 
  killid=$(cat /home/xiaofang/test/tmp.txt) 
  for killtmp in $killid 
  do  
  /bin/kill -9 $killtmp 2> /dev/null 
  done 

抱歉!评论已关闭.