上一文中记录了shell相关的知识点,本文就之前的知识点完成简单的例程:
如下:
#! /bin/bash
echo "hello 你好!"
echo //-------字符串,数组---------------------------------
#定义字符串
str0='abc'
str1="${str0}defg123"
str=""$str0"${str1}"
#输出字符串
echo str=$str
#输出字符串长度
echo "字符串str长度为: ${#str}"
#输出子字符串0到2的字符
echo 字符串str中0到2的字符为: ${str:0:2}
#定义数组
array=(abc 123 dss 456)
#读取数组元素
echo "字符串array中0的元素为: ${array[0]}"
echo "字符串array中的所有元素: ${array[@]}"
#获取数组长度
echo "字符串array的长度为 : ${#array[@]}"
echo array_length=${#array[*]}
echo //---------------打印输出--------------------------------------
#read 使用
#echo-不换行使用
echo -e "输入文件名:\c"
read filename
#echo-输出到文件
echo “写到文件中的内容、、。。,。,。” > $filename
#printf使用
printf "%s %s\n" printf 练习0
printf "printf 练习1\n"
echo //-------------条件,循环----------------------------------------
#if -else if else使用
a=10
b=20
if [ $a == $b ]
then
echo "a等于b"
elif [ $a -gt $b ]
then
echo "a大于b"
elif [ $a -lt $b ]
then
echo "a小于b"
else
echo "故障"
fi
#for循环使用
echo -e "for循环值为: \c"
for loop in 1 2 3
do
echo -e "$loop \c"
done
printf "\n"
#while循环使用
cnt0=1
echo -e "cnt0的值为: \c"
while(( $cnt0<=3 ))
do
echo -e "$cnt0 \c"
let "cnt0++"
done
printf "\n"
#until循环使用
cnt1=1
echo -e "cnt1的值为: \c"
until [ $cnt1 -eq 3 ]
do
echo -e "$cnt1 \c"
cnt1=`expr $cnt1 + 1`
done
printf "\n"
echo //--------case,无限循环-------------------------------
#case选择语句使用
sel0=2
case $sel0 in
1) echo sel0为1
;;
2) echo sel0为2
;;
3) echo sel0为3
;;
*) echo sel0为其他值
;;
esac
#while无限循环,break,continue使用
sel1=1
while :
do
echo while循环开始
case $sel1 in
1) echo sel1为1
;;
2) echo sel1为2
continue
echo continue执行失败
;;
3) echo sel1为3
;;
4) echo sel1为其他值
break
;;
esac
echo while循环1
break
echo while循环完成
done