1,基本的shell编程入门
接下来我们会写一个小例子来介绍如何写一个简单易懂的linux shell小脚本,我们给这个脚本其名字first.sh。接下来我说明实际的开发步骤。
使用vi编辑器创建文件,vi filename 来创建。
编写脚本
#!/bin/sh
#This is my first linux shell program
a="Hello World"
echo $a" new People coming Linux"
默认创建好的shell脚步默认没有可执行权限,我们要赋予可执行权限,chmod +x filename.
执行shell脚本./filename.sh
2,shell中的if控制结构
#! /bin/sh
#This shell is tell you how to use if to controll execute direct
a=13
if [ $a -lt 10 ];then
echo "a is bigger than 10"
else
echo "a is litter than 10"
fi
说明,if的条件判断必须加分号。if结束时反写if。
3,脚本调用另外的脚本,先判断脚本是否可以执行,如果可以执行则执行,否则提示消息。
#! /bin/sh
#This is use another shell script
file=test.sh
if [ -x "$file" ] ; then
./$file
else echo "This file can't execute"
fi
4,shell读取控制台用户输入信息,如两个数,根据两个数字的大小输出响应的提示。
read命令是一个内置命令,用于从终端或文件读取输入。read命令读取一行数据,到换行符截至。
read variable_name,从标准输入读取一行数据赋值给对应的变量。
read first last 从标准输入读取一行,直至遇到第一空白符或还行符,把前半部分赋值值给first把后半部分赋值给last。
read -a array 读入一组词,依次赋值给数组array。
read -p ;打印提示符,等待输入,并将输入赋值给REPLY
#! /bin/sh
#This is test read from console
echo "please input first variable"
read var_first
echo "please input second variable"
read var_second
if [ $var_first>$var_second ];then
echo "This is a bigger show"
else echo "This is a letter show"
fi
5,创建空白文档
touch filename
6,for循环结构
for variable_name in array
do
echo $variable_name
done