Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Linux Shell脚本编程入门

最近在学shell,记录一下。if语句的使用:
1.判断两个参数大小
#!/bin/sh#a test about if statementa=10b=20if [ $a -eq $b ];thenecho "parameter a is equal to parameter b"elif [ $a -le $b ];thenecho "parameter a is less than parameter b"elif [ $a -gt $b ];thenecho "parameter a is greater than parameter b"elseecho "i don"t know the result!"fi
2.执行脚本时动态传递参数$1、$2、$3...分别代表接收到的参数$0 表示程序的名称$#传递给程序的总的参数数目 $? 上一个代码或者shell程序在shell中退出的情况,如果正常退出则返回0,反之为非0值$*传递给程序的所有参数组成的字符串$@ 以"参数1" "参数2" ... 形式保存所有参数 $$ 本程序的(进程ID号)PID $!上一个命令的PID
脚本#!/bin/sh#a test about if statementa=$1b=$2if [ $a -eq $b ];thenecho "parameter a is equal to parameter b"elif [ $a -le $b ];thenecho "parameter a is less than parameter b"elif [ $a -gt $b ];thenecho "parameter a is greater than parameter b"elseecho "i don"t know the result!"fi执行效果:

3.for循环的使用
#!/bin/bash#a test about for and while statementfor i in {1..5}do echo "hello world"$idone注意:这里sh不支持这种写法,要用bash来运行sh支持这种写法:#!/bin/sh#a test about for and while statementfor i in 1 2 3 4 5do echo "hello world"$idone
4.在/root/test/test2文件夹中创建100文件夹,名称为test1~test100
#!/bin/bash#create 100 folder in /root/test/test2for i in {1..100}do`mkdir ./test2/test$i`done
5.编写乘法表,根据输入参数来输出某个数的乘法表
#!/bin/bashfor((i=1;i<=$1;i++)){for((j=1;j<=${i};j++)){ ((ret=${i}*${j})) echo -ne ${i}*${j}=$ret" " }echo}注意:参数中的-n表示输出后不换行,e表示支持转义字符运行效果:
Linux Shell在while中用read从键盘输入  http://www.linuxidc.com/Linux/2015-06/118831.htmLinux Shell 程序调试  http://www.linuxidc.com/Linux/2015-07/119880.htmLinux Shell脚本面试25问  http://www.linuxidc.com/Linux/2015-04/116474.htmLinux/Unix Shell 参数传递到SQL脚本 http://www.linuxidc.com/Linux/2013-03/80568.htmShell脚本中参数传递方法介绍 http://www.linuxidc.com/Linux/2012-08/69155.htmShell脚本传递命令行参数 http://www.linuxidc.com/Linux/2012-01/52192.htmLinux Shell 通配符、转义字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm 本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/121394.htm