Shell是一个用C语言编写的一种应用程序,他是用户操作linux的桥梁,也可以算做一种程序设计语言。Shellshell脚本实质上是不同的概念,shell是用c语言写的一种应用程序,有能力的人甚至可以自己开发出一个shellShell脚本可以简单的理解成linux命令的一种集合,有时候我们要在linux上做一项安装软件的任务,涉及到100linux命令,那么把这100条命令写成shell脚本,然后去一键执行安装,这样就方便多了。因为写好了之后方便下次安装或者是交给团队里的其他同事去安装。

 

#!/bin/bash
#---变量的定义---#
name="Linux"
echo ${name}  #输出Linux
name=Linux 
echo $name    #输出Linux
#---变量的定义---#
#---for循环---#
for name in Ada Alex Amy Bob Cris Emma 
do
  echo "hello my name is ${name},how are you doing"
done

sum=0
for((i=0;i<=100;i++))
do
  sum=$(expr $sum + $i)  
  #这里有两个要注意的地方
  #1.两个数相加的话,加号的左右两边都要严格加上空格,这里跟一般的编程写法不同 
  #2.所有的四则运算都要加上expr,不然就会出错
done
echo "the sum is ${sum}"

for i in {1..10}
do
  echo "this is $i"
done

sum=0
for i in `seq 100` #``符号等同于$()
do
  sum=$(expr $sum + $i)
done
echo "the second for,sum is ${sum}"
#---for循环---#

#---获取字符串长度---#
string='abcdefg'
echo "the length of string is ${#string}"
#---获取字符串长度---#
#---提取子字符串---#
string='His name is Alex'
echo ${string:0:3}
#---提取子字符串---#

string='He is a boy'
echo `expr index "$string" is`

 

执行结果

Linux
Linux
hello my name is Ada,how are you doing
hello my name is Alex,how are you doing
hello my name is Amy,how are you doing
hello my name is Bob,how are you doing
hello my name is Cris,how are you doing
hello my name is Emma,how are you doing
the sum is 5050
this is 1
this is 2
this is 3
this is 4
this is 5
this is 6
this is 7
this is 8
this is 9
this is 10
the second for,sum is 5050
the length of string is 7
His
4

 

shell中的数组

array1=(1 2 3 "name" "age")#数组的定义
echo ${array1[1]}  #数组的第1个参数,值为2
echo ${#array1[*]}  #数组的长度,值为5
echo ${array1[*]}   #数组的所有元素
for i in ${array1[*]}   #循环遍历数组中所有元素
do
  echo $i
done