什么是shell脚本,首先它是一个脚本,并不能作为正式的编程语言,说白了就是shell脚本就是一些命令的集合。
凡是自定义的脚本建议放到/usr/local/sbin/目录下,这样的好处是方便管理和维护,且利于以后交接给接替你的管理员。
shell脚本的结构
#cat first.sh
#! /bin/bash
## This is my first shell script.
date
echo "Hello world!"
脚本要以#! /bin/bash开头,代表的意思:该文件是使用的是bash语法,如果不使用该行也是可以的,但是如果把这个脚本放到一个默认shell并非bash的系统里,那么这个脚本很有可能是不能成功执行的。
还可以适当在脚本中使用#写一些脚本相关的注释内容,如作者、创建日期或者版本等。这些并不是shell脚本一定要的,只是为了统一管理,规范化。 shell脚本的几种执行方式
如果想要保留2位小树,可以这样实现。
# echo "scale=2;8/3"|bc
2.66 shell用户交互
shell脚本可以实现让用户输入一些字符串(read命令)或者让用户去选择(select语句)的行为。
read命令
# cat read.sh
#! /bin/bash
## Using 'read' in shell script.
read -p "Please input a number: " x
read -p "Please input another number: " y
sum=$[$x+$y]
echo "The sum of the two numbers is: $sum"
read命令类似与visualbasic的input函数,作用是产生一个“输入行”,将用户输入的字符串赋值给read命令语句后的变量。
# sh read.sh
Please input a number: 2
Please input another number: 10
The sum of the two numbers is: 12
select语句
select 循环提供了一个简单的方法来创建一个编号的菜单,用户可从中选择。它是有用的,当你需要从列表中选择,要求用户选择一个或多个项目。
select 表达式是一种bash的扩展应用,动作包括:
l 自动用1,2,3,4列出菜单(没有echo指令,自动显示菜单)
l 自动read输入选择(没有 read指令,自动输入)
l 赋值给变量(没有赋值指令,自动输入数字后,赋值字符串给变量)
语法格式:
selectvariable in value1 value2 value3 …
do
command
done
例子:
# cat sel.sh
#! /bin/bash
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "FreeBSD" "Other"
do
break
done
echo "You have selected $var"
# sh sel.sh
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 2
You have selected Gnu Hurd
select本身就是一个循环,break就是当选择后,就跳出循环。
当变量内容含有空格时,应该将其用""括起来。
select一般和case语句结合使用,以上面一个例子为例,将它优化下:
# cat sel.sh
#! /bin/bash
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "FreeBSD" "Other"
do
case $var in
Linux)
break;;
"Gnu Hurd")
break;;
"Free BSD")
break;;
Other)
break;;
*)
echo "Please enter anumber:(1-4)";;
esac
done
echo "You have selected $var"
select虽然循环却在第一次选择之后不再显示菜单,只循环输入。
# sh sel.sh
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 6
Please enter a number:(1-4)
#? 8
Please enter a number:(1-4)
#? 3
You have selected Free BSD
Shell脚本预设变量
# cat option.sh
#! /bin/bash
sum=$[$1+$2]
echo "$0$1"+"$2"="$sum"
# sh option.sh 2 3
option.sh 2+3=5
$#表示参数的个数,$0是脚本本身的名字,$1是执行脚本时跟的第一个参数,$2是执行时跟的第二个参数,$3是…当然一个shell脚本的预设变量是没有限制的。 if语句
if语句是逻辑判断语句。
if几种语法格式:
1) if 判断语句;then command;fi
2) if 判断语句;then command;else command;fi
3) if 判断语句
then
command
fi
4) if 判断语句
then
command
elif 判断语句
then
command
else
command
fi
例子
# cat if1.sh
#! /bin/bash
read -p "Please input your score: " a
if ((a,