shell脚本基本语法

以下是初学shell脚本练习过程,涉及到内容的输出、基本的计算、条件判断(if、case)、循环控制、数组的定义和使用、函数定义和使用

shell脚本内容:

#! /bin/bash
echo "current sh file name $0 ${0} $0_file"
echo $$

#加乘除运算
value=`expr 2 + 2`
echo "total value is:${value}"
a=10
b=20
ab=`expr $a * $b`
echo "$a * $b = $ab"

#echo "please inputi c:"
#read c
#ab=`expr $a / $c`
#echo "$a/$c=${ab}"


#if条件判断
if [ $a == $b -o $a -gt 0 ];
then
  echo "a==b or a>0"
else
  echo "a!=b"
fi

#字符段判断
str="dog,cat,fish,cattle,pig,rabbit"
echo `expr index $str fish`


file="/usr/tmp/file.test"
if [ -e ${file} ]
then
  if [ -w $file ]
  then
    echo "file enable write"
  fi
  if [ -s $file ]
  then
    echo "file is not empty"
  else
    echo "file is empty"
  fi
fi

#循环控制使用,含有continue和break
for ((i=0;i<3;i++))
do echo $i
done

#数组的2种定义和使用
#array=(a b c)
array[0]=a
array[1]=b
array[2]=c
for i in ${array[@]}
do echo $i
done
echo "array length is" ${#array[@]}"; array contain element is:" ${array[@]}


j=5
while [ $j -lt 7 ]
do
  echo $j
  j=$(($j+1))
done


#case条件判断
name=bird
case "$name" in
dog)
  echo $name;;
cat)
  echo $name;;
fish)
  echo $name;;
rabbit)
  echo $name;;
esac


#函数的定义,$1表示第一个函数参数
total=0
count(){
  total=$(($1+$2))
}

#函数的调用
count 10 20
echo "call count function 10+20=$total"

#将结果输出到文件
echo ${array[@]} >> /usr/tmp/file.test


#巧用<<EOF EOF 做注释
<<EOF

read var
echo "You input is $var"
EOF


运行结果:

[root@VM_64_7_centos tmp]# ls -l
total 8
---------- 1 root root 616 Dec 18 13:48 test.sh
[root@VM_64_7_centos tmp]# bash test.sh

current sh file name ./test.sh ./test.sh ./test.sh_file
10470
total value is:4
10 * 20 = 200
a==b or a>0
9
file enable write
file is not empty
0
1
2
a
b
c
array length is 3; array contain element is: a b c
5
6
call count function 10+20=30

[root@VM_64_7_centos tmp]# ./test.sh
-bash: ./test.sh: Permission denied


bash test.sh(sh test.sh)和./test.sh和区别
前者不需要任何权限都可以执行shell脚本,但是后者文件需要有x可执行的权限。

原文地址:https://www.cnblogs.com/advancing/p/8058912.html