Shell编程
执行方式
.sh文件执行可以分为三种:第一种是直接调用当前目录下的sh,但是必须要赋予x权限;第二种为sh调用方式它可以没有执行权限,但是和第一种一样没有进程互通的特点,要用export申明才可以;第三种是直接调用,它会从最根部调用,因此可以直接使用全部的变量定义:
./test.sh
sh test.sh
source test.sh
变量操作
for file in $(ls/etc) #循环
echo $name #用$ 提取,避免字符串
url = "www.baidu.com" #赋值
readonly url #只读
read name #读取
unset name #删除
字符串
str1="hello world!" #单双引号赋值
str2=$str1 #赋值,赋予与str1相同的
str3="$str2 555" #str3=str2+ 555
str4='$str2 555' #不进行转义,与str3的区别
echo ${#str1} #输出str1的长度
echo ${str1:2:3} #从第二位开始数三位
数组
favs=("1","2",$a) #定义数组
echo ${favs[1]} #输出favs[1]
echo ${favs[@]} #输出全部的值
注释
#这是一行注释
#下面是多行注释:
:<<EOF
asdsad
EOF
运算符
val=`expr 2 + 2`
echo "两数之和为 : $val"
if [ $a -eq $b ]
then
echo "$a -eq $b : a 等于 b"
else
echo "$a -eq $b: a 不等于 b"
fi
if [[ $a -lt 100 && $b -gt 100 ]]
then
echo "返回 true"
else
echo "返回 false"
fi
if [ -d $file ]
then
echo "文件是个目录"
else
echo "文件不是个目录"
fi
分支
if:
if condition1
then
command1
elif condition2
then
command2
else
command3
fi
Case:
case dig in
1)
command1
...
commandn
;;
2)
command1
...
commandn
;;
esac
For:
for var in item1 item2 ...
do
command
done
While:
while condition
do
command
done
函数:
func(){
echo " $1 " //打印第一个参数
echo " $# " //打印长度
echo " $* " //打印所有
return `expr $1 + $2`
}
func 1 2 3 //调用函数