本节linux shell/ target=_blank class=infotextkey>shell脚本编程分为二部分:1,shell基本操作,2,shell结构化命令实例。
一、基本操作
1、echo $SHELL
2、重定向 > >> < <<
wc << test
> hello world
> just do it
> over
> test
3 6 28
3、管道 command1 | command2 command1的输出作为command2的输入
4、数学运算
expr num1 opt num2 (opt = + - * / >= <= > < != | & %)
$[num1 opt num2]
解决浮点数运算使用bc的scale: c=`echo "scale=5;$a / $b" | bc`
5、每个命令都有退出状态码 $?
0:命令成功结束
gt 0: 命令出错
exit 0
二、结构化命令
复制代码 代码示例:
#!/bin/bash
#descrip: it's a test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
if grep $USER /etc/passwd
then
echo 'SUCCESS'
else
echo 'FALIUR'
fi
exit 0
1、test的condition []
数值比较: -eq -ge -gt -le -lt -ne
字符串比较:= != > < -n(length is not zero) -z (注:大于小于得转义,否则成重定向)
文件比较:-d -e -f -r -s -w -x -O(is owned by current user?) -G(default group same as current group) -nt(newer than) -ot(older than)
2、复合条件
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
3、高级特性:(( expresion )) [[ strExpression字符串比较 ]]
expression:(++ -- ! ~ ** << >> & | && || ) (> < = ) (注:> < 不需要转义)
strExpression:pattern matching
4、case
复制代码 代码示例:
case var in
pattern1 | pattern2) command1;;
pattern3) command2;;
...
*) default command;;
esac
5、for while util
for var in list
do
command
done
更还分隔符:
空格:
制表:
换行:IFS=$'n' $'t'
IFS.old=IFS
...
IFS=IFS.old
例1:
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
for file in /data/*
do
if [ -d $file ]
then
echo $file is a dictory
elif [ -f $file ]
then
echo $file is a file
fi
done
exit 0
例2,
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
for((i = 1; i <= 10; i++))
do
echo "loop test: "$i
done
var=10
while [ $var -gt 0 ]
do
echo "while test: "$var
(( var-- ))
done
n=1
until [ $n -eq 10 ]
do
echo "until test: "$n
(( n++ ))
done
exit 0
例3:
复制代码 代码示例:
#!/bin/bash
#descrip: test
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/xiaolong.hou/bin:/usr/local/jdk1.7/bin:/usr/local/maven/bin:/usr/local/hadoop-1.2.1/bin
IFSOLD=$IFS
IFS=$'n'
for line in `cat /etc/passwd`
do
echo "line: "
IFS=:
for field in $line
do
echo " "$field
done
done
IFS=$IFSOLD
exit 0
您可能感兴趣的文章: