有起要注意空格等问题,这个一开始学的时候特别容易出错,然后导致查了半天!!
1-helloworld.sh
#!/bin/bash
#使用/bin/bash来解析脚本
echo "helloworld"
2-变量.sh
#!/bin/bash
num=10
name="jack"
age=22
sex='male'
echo $num
echo "name : $name age : $age sex : $sex"
echo "输出命令行参数"
echo $1
echo $2
echo $3
echo "共有$#个命令行参数"
echo "所有参数:$*"
#export AA=100 #环境级变量 作用域:当前终端
#echo "export AA=100" >> ~/.profile #用户级变量 作用域:相同用户
#source ~/.profile
#echo "export AA=100" >> /etc/profile #系统级变量 作用域:整个系统
#source /etc/profile
echo "打印环境变量"
echo $AA
3-数学运算.sh
#!/bin/bash
num=100
let num=num+100
echo $num
num=100
num=$[num+100]
echo $num
num=100
num=$((num+100))
echo $num
num=100
num=`expr $num + 100`
echo $num
4-数组.sh
#!/bin/bash
array1=(1 2 3 4 5)
array2=('a' 'b' 'c' 'd' 'e')
array3=("1111" "2222" "3333")
echo ${array1[0]}
echo ${array2[0]}
echo ${array3[0]}
echo ${array3[@]} #访问所有元素
echo ${#array1[@]} #打印数组元素个数
echo ${!array1[@]} #打印所有的下标
echo ${array1[@]:1} #从第二个元素开始打印
echo ${array1[@]:1:2}
#关联数组
echo "**************"
declare -A array4
declare -A array5
array4[name]="jack"
array4[age]=22
array4[sex]="male"
array5=([name]="tom" [age]=23 [sex]="male")
echo ${array4[@]}
echo ${array5[@]}
5-判断语句.sh
#!/bin/bash
num=$1
if [ -z $num ]; then #长度为0则成立
echo "请输入参数"
exit
fi
if [ $num -eq 100 ]; then #判断相等
echo "等于100"
elif [ $num -gt 100 ]; then
echo "大于100"
elif [ $num -lt 100 ]; then
echo "小于100"
fi
6-case.sh
#!/bin/bash
read num
case $num in
[a-z])
echo "小写字母";;
[A-Z])
echo "大写字母";;
[0-9])
echo "数字";;
*)
echo "未知";;
esac
7-while.sh
#!/bin/bash
while read i
do
echo $i
done < $1
8-for.sh
#!/bin/bash
for ((i=0;i<5;i++))
do
mkdir $i
cd $i
echo "this is $i" > $i
cd ..
done
for i in 0 1 2 3 4
do
cd $i
echo "hello $i" > $i
cd ..
done