常用的基本shell语句

来源:互联网 发布:淘宝找西瓜刀打什么 编辑:程序博客网 时间:2024/04/29 20:32
#
# example1
# for 循环一般用法
#


# 不支持
val=`ls`
for i in $var;do \
echo $i; \
done
echo "##################1.1####################"


# 不支持
for i in $var;do echo $i;done
echo "##################1.2####################"


# 支持
var=`ls`
for i in $var 
do
echo $i
done
echo "##################1.3####################"


str="abcdef"
len=`expr length $str` # expr -- help 可以查询其作用
for ((i=0;i<$len;i++))
do
char=${str:$i:1}    # 取子串用"{}" str:母串; $i:起始位置; i:子串长度
echo $char
done
echo "##################1.4####################"


#
# example2
# 条件判断
#

if [ -d ~ ] ;then echo "it's a directory";fi
echo "##################2.1####################"


if [ -d ~ ] 
then
echo "it's a directory"
fi
echo "##################2.2####################"


if [ -d ~ ]; then
echo "it's a directory"; \
fi


echo "##################2.3####################" 


if [ -f ~ ]
then echo "it's a file!"
elif [ -d ~ ]
then echo "it's a directory"
elif [ 1 -lt 2 ]
then echo "it's ok"
fi


echo "##################2.4####################" 


if [ -f ~ ]
then echo "it's a file!"
else
echo "it's a directory"
fi
echo "##################2.5####################" 


#
# example3
# switch case
#

case a in
   a) echo a;;
   b) echo b;;
   c) echo c;;
   *) echo err;;
esac
echo "##################3.1####################" 


#
# example4
# 条件判断的一般类型
#


# 判断文件是否存在

file=shell_test.sh
if [ -e $file ]
then echo "yes"
fi
echo "##################4.1####################" 


# 判断字符串是否相等
str1="abc"
str2="abc"
file=shell_test.sh
if [ $str1 == $str2 ]
then echo "yes"
fi
echo "##################4.2####################"


# 判断数字是否相等
int1=2
int2=`expr 1 + 1`
file=shell_test.sh
if [ $int1 -eq $int2 ]
then echo "yes"
fi

echo "##################4.3####################"


# 删除隐藏文件,除去“." 和".."

files=`ls -a`;for i in $files;do if [ $i != "." ] && [ $i != ".." ]; then rm -f $i;fi;done;


# 递归删除文件

$ find -type f -name "*.o" -exec rm -f {} \;

原创粉丝点击