1.以下脚本名称为test.sh,加权限chmod +x test.sh,./test.sh 或 sh test.sh 执行
#!/bin/bash
#字符串定义
var_test='you are my life'
var_a="hello"
var_b=null
#数组定义
arr_test=(
'you'
'are'
'my'
'sunsine'
)
#字符串普通输出
echo $var_test
#数组取值
echo ${arr_test[3]}
#取数组全部的值
echo ${arr_test[@]}
#字符串截取
echo ${var_test:0:3}
#判断字符串长度,-a 且;-o 或者
echo ${#var_test}
#布尔运算符
if [ ${#var_test} == 15 -a ${arr_test[2]} = 'my' ];then
echo "It's true"
else
echo "It's false!"
fi
#-z 判断字符串长度是否为0,为0返回true
if [ -z $var_a ];then
echo "The length is 0"
else
echo "The length is not 0"
fi
#逻辑运算符
if [[ ${#var_test} == 15 && ${arr_test[2]} = 'my' ]]
then
echo "It's true"
else
echo "It's false!"
fi
#检测字符串是否为空
if [ $var_b ]
then
echo "yes"
else
printf "no\n"
fi
num1=100
num2=50
if test $[num1] -eq $[num2]
then
echo '两个数相等!'
else
echo '两个数不相等!'
fi
#for循环
for aa in $var_test
do
echo $aa
done
#while循环
#let 命令是 BASH 中用于计算的工具,用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量。如果表达式中包含了空格或其他特殊字符,则必须引起来
mm=1
while(( $mm<=5 ))
do
echo $mm
let "mm++"
done
#无限循环
while true
do
command
done
#while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量FILM,按<Ctrl-D>结束循环
echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的网站名: '
while read FILM
do
echo "是的!$FILM 是一个好网站"
done
#获取执行脚本参数,例 sh test.sh param1,对应$1的值为param1
echo "Shell 传递参数实例!"
echo "执行的文件名:$0"
echo "第一个参数为:$1"
echo "第二个参数为:$2"
#函数和case判断
fun01(){
echo 'function01 excute'
}
fun02(){
echo 'function02 excute'
}
noinput(){
echo 'please input 1 or 2'
}
read var_in
case $var_in in
1)
fun01
;;
2)
fun02
;;
*)
noinput
esac
日期格式化输出
[root@root ~]# date "+%Y-%m-%d"
2013-02-19
[root@root ~]# date "+%H:%M:%S"
13:13:59
[root@root ~]# date "+%Y-%m-%d %H:%M:%S"
2013-02-19 13:14:19
[root@root ~]# date "+%Y_%m_%d %H:%M:%S"
2013_02_19 13:14:58
[root@root ~]# date -d today
Tue Feb 19 13:10:38 CST 2013
[root@root ~]# date -d now
Tue Feb 19 13:10:43 CST 2013
[root@root ~]# date -d tomorrow
Wed Feb 20 13:11:06 CST 2013
[root@root ~]# date -d yesterday
Mon Feb 18 13:11:58 CST 2013