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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值