初识Shell Scripts编程--最最简单的shell例子

5 篇文章 0 订阅

前段时间因为要往一个文件写入一系列随机数给大家用,自己用C语言写了一个,把源文件发给大家,然后大家还要编译,运行,有时候里面的代码需要修改重新编译运行,很是麻烦,其实这些都可以用简单的Shell Scripts来完成。

来看第一个程序,sh01.sh:显示"Hello World!"

#!/bin/bash      #这个一行在宣告这个script使用的shell名称,因为我们用的是bash,所以这么写。除了的[#!]这一行是用来宣告shell之外,其他的#都是[批注]
#program:
#	This program shows "hello world!" in your screen
#History:
#	2013/6/28 Leaguenew First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "Hello World! \a \n"
exit 0


脚本的执行:1.sh sh01.sh;2.chmod a+x sh01.sh ; ./sh01.sh ;

执行结果:


为了代码清晰简单,下面的代码就省去了对程序功能的介绍,历史版本,设置PATH等。


sh02.sh--通过read -p命令来通过terminal和用户交互,输入信息等;

#!/bin/bash

read -p "please input your first name: " firstname	 	#for user to input
read -p "please input your last name: "	lastname		#for user to input
echo -e "\nyour full name is : $firstname $lastname "	#show the result
执行结果:


sh03.sh--输入文件名filename,通过date生成文件名为当天,前一天,前两天的文件。

#!/bin/bash

echo -e "I will use 'touch' command to create 3 files."  #显示信息
read -p "Please input your filename: " fileuser          #提示使用者输入

date1=$(date --date='2 days ago' +%Y_%m_%d)     #前两天的日期
date2=$(date --date='1 days ago' +%Y_%m_%d)     #前一天的日期
date3=$(date +%Y_%m_%d)                         #今天的日期
file1=${filename}${date1}                       #以下三行设定档名
file2=${filename}${date2}
file3=${filename}${date3}

touch "$file1"                                  #建立文档
touch "$file2"
touch "$file3"

运行结果:



sh04.sh--利用$((计算式))来进行数值运算,输入两个变量,输出相乘的结果:

#!/bin/bash

read -p "please input the first number:" firstnum       #依次输入两个值
read -p "please input the second number:" secondnum

declare -i total=$firstnum*$secondnum                   #计算结果
echo -e "the result is ==> $total"

输出结果:



介绍一下script针对参数设定的变量名称:

比如执行一条命令:./script.sh   opt1   opt2   opt3   opt4
                                        $0      $1      $2      $3      $4

执行的脚本明为$0这个变量,接着第一个参数相当于$1...相当于C语言中执行:./a.out argv[1] argv[2] argv[3]

$#   :代表后接的参数『个数』,以上表为例这里显示为『4 』;
$@ :代表『"$1" "$2" "$3" "$4" 』之意,每个变量是独立的(用双引号括起来);
$*   :代表『"$1c$2c$3c$4" 』,其中c 为分隔字符,预设为空格键, 所以本例中代表『"$1
$2 $3 $4" 』之意。

sh07:

#!/bin/bash

echo "The script name is ==> $0"                #文件名
echo "Total parameter number is ==> $#"         #打印参数个数
[ "$#" -lt 2 ] && echo "The number of parameter si less than 2. stop here." && exit 0


echo "Your whole parameter is ==> '$@' "        #打印全部参数
echo "The 1st parameter ==> $1 "<span style="white-space:pre">	</span>     
echo "The 2st parameter ==> $2 "
echo "The 3st parameter ==> $3 "<strong>
</strong>
运行结果:





下面介绍一下条件判断式if......then......fi

sh06-2.sh--通过用户的输入判断是y/Y还是n/N,还是都不是:

#!/bin/bash

read -p "Please input (Y/N) : " yn
if [ "$yn" == "Y" -o "$yn" == "y" ] ; then        #判断输入的是Y/y,如果是的话,输出:OK,continue
		echo "OK , continue" 
		exit 0
fi
if [ "$yn" == "N" -o "$yn" == "n" ] ; then        #判断输入的是N/n,如果是的话,输出:Oh,interrupt!
	echo "Oh , interrupt!" 
	exit 0
fi

echo "I don't know what your choice is"  && exit 0  #如果以上两个条件都不成立,那么输出。。。

注:if后面的[]前后要有空格。


多重复杂条件判断式:

if[ 体检判断式 ] ; then

          当条件判断式成立时,可以进行的指令工作内容;

else 

          当条件判断式不成立时,可以进行的指令工作内容;

fi


还有if...elif...elif...else

if[ 条件判断式一 ] ; then

          当条件判断式一成立时,可以进行的指令工作内容;

elif[ 条件判断式二 ] ; then

          当条件判断式二成立时,可以进行的指令工作内容;

else 

          当条件判断式二成立时,可以进行的指令工作内容;

fi

#!/bin/bash

read -p "Please input (Y/N) : " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ] ; then 
		echo "OK , continue" 
elif [ "$yn" == "N" ] || [ "$yn" == "n" ] ; then
	echo "Oh , interrupt!" 
else  
	echo "I don't know what your choice is" 
fi

利用case...esac判断:

语法形式:

case $变量名称in                       <==关键词为case ,还有变数前有钱字号
        "第一个变量内容")              <==每个变量内容建议用双引号括起来,关键词则为小括号)
                    程序段
                    ;;                             <==每个类别结尾使用两个连续的分号来处理!
        "第二个变量内容")
                    程序段
                     ;;
       *)                                        <==最后一个变量内容都会用* 来代表所有其它值
                    不包含第一个变量内容与第二个变量内容的其它程序执行段
                     exit 1
                     ;;
esac                                          <==最终的case 结尾!『反过来写』思考一下!


sh12.sh--判断输入的参数是one , two , three :

#!/bin/bash

echo "This program will print your selection!"
read -p "Input your choice:" choice
case $choice in
	"one")
		echo "Your choice is one"
		;;
	"two")
		echo "Your choice is two"
		;;
	"three")
		echo "Your choice is three"
		;;
	*)
		echo "Your choice should be one/two/three"
		;;
esac

运行结果:



利用function功能:

sh12-3.sh:

#!/bin/bash

function printit()
{
	echo "Your choice is $1"
}

echo "This program will print your selection!"
read -p "Input your choice:" choice
case $choice in
	"one")
		printit $choice;
		;;
	"two")
		printit $choice;
		;;
	"three")
		printit $choice;
		;;
	*)
		echo "Your choice should be one/two/three"
		;;
esac<strong>
</strong>



循环(loop):

while [ condition ]                         <==中括号内的状态就是判断式,当condition成立一直循环。
do                                                 <==do 是循环的开始!
          程序段落
done                                             <==done 是循环的结束

until [ condition ]                           <==当condition成立,终止循环。
do
         程序段落
done


sh14.sh--计算1+2+3...+100:

#!/bin/bash

s=0
i=0
while [ "$i" != "100" ]
do
	i=$(($i+1))                 # $((计算表达式))
	s=$(($s+$i))	
done

echo "The result of '1+2+3..100' is  ==> $s "

运行结果:



for...do...done(固定循环):


语法一:

for var in con1 con2 con3 ...
do
          程序段
done

sh15.sh:

#!/bin/bash

for animal in dog cat elephant
do 
	echo "There are ${animal}s"
done
运行结果:



语法二:

for...do...done的数值处理:
for (( 初始值; 限制值; 执行步阶))
do
        程序段
done


sh19.sh:根据你的输入数值n来从1加到n:

#!/bin/bash

read -p "please input a number , I wil count for 1+2..+your_input:" nu

s=0
for ((i=1;i<=$nu;i++))
do
	s=$(($s+$i))
done

echo "The result of '1+2..$nu' is ==> $s"
执行结果:



sh20.sh:创建文件和删除文件:

将下面两句命令转换成为代码:

touch file{0..9}
rm -rf file{0..9}
将问题复杂化:

#!/bin/bash

function create_file()
{
	touch file{0..9}
}

function delete_file()
{
	for i in {0..9}
	do
		rm -rf file${i} #string connect
		echo "remove file $i"
	done
}

create_file
delete_file


sh21.sh:获取shell ip

<pre name="code" class="python">#!/bin/bash
ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ":" -f 2 | cut -d ' ' -f 1)"
echo $ip

 

22 bash shell下处理json的工具:jq

>yum -y install jq

总结:

· shell script 是利用shell 的功能所写的一个『程序(program)』,这个程序是使用纯文字文件,将一些shell 的语法与指令(含外部指令)写在里面, 搭配正规表示法、管线命令与数据流重导向等功能,以达到我们所想要的处理目的· 在Shell script 的档案中,指令的执行是从上而下、从左而右的分析与执行;· shell script 的执行,至少需要有r 的权限,若需要直接指令下达,则需要拥有r 与x 的权限;· 良好的程序撰写习惯中,第一行要宣告shell (#!/bin/bash) ,第二行以后则宣告程序用途、版本、作者等· 对谈式脚本可用read 指令达成;· 要建立每次执行脚本都有不同结果的数据,可使用date 指令利用日期达成;· script 的执行若以source 来执行时,代表在父程序的bash 内执行之意!· 在script 内,$0, $1, $2..., $@ 是有特殊意义的!· 条件判断式可使用if...then 来判断,若是固定变量内容的情况下,可使用case $var in ...esac 来处理· 循环主要分为不定循环(while, until) 以及固定循环(for) ,配合do, done 来达成所需任务!现在完成一个任务:就是给定一组人的姓名(abc,def,ghi,jkl),输入一个数n,得到一个文件,文件内容为:

1,abc

2,jkl

3,def

。。。

等;

代码:

#!/bin/bash

read -p "please input the number of loops : "  n

locations=(Shanghai Beijing Suzhou Wuxi Xuzhou)         #设置数组locations,其中有五个元素,每个元素都是字符串的名字

num=${#locations[*]}                                    # "<span style="font-family: Arial, Helvetica, sans-serif;">#locations[*] “</span>代表数组元素的数量

for ((i=1;i<=$n;i=i+1))
do 	
	echo  "$i , ${locations[($RANDOM)%($num)]}" >> filename          # "<span style="font-family: Arial, Helvetica, sans-serif;">$RANDOM</span>"是linux自带的系统随机数变量
done<strong>
</strong>
执行结果:


生成的filename:


        至此,最最简单的shell scripts编写方法就到这里了,shell的功能十分强大,能提高我们的工作效率,所以如果要进一步学习还有很长的路走。


转载请注明:http://blog.csdn.net/lavorange/article/details/9631759 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值