当前位置: 首页 > 编程日记 > 正文

「学习笔记-Linux」学习Shell Script

学习Shell Script

Table of Contents

  • 1 什么是Shell Scipt
    • 1.1 程序书写
    • 1.2 程序执行
  • 2 简单Shell练习
    • 2.1 例1 接收用户输入
    • 2.2 例2 按日期建立相似名字的文件
  • 3 判断式
    • 3.1 测试文件是否存在
    • 3.2 test常用选项
      • 3.2.1 文件类型
      • 3.2.2 权限
      • 3.2.3 文件新旧比较
      • 3.2.4 整数,字符串,多重条件判断
    • 3.3 使用[]判断
  • 4 Shell Script 参数
  • 5 条件表达式
    • 5.1 if 结构
    • 5.2 if else 结构
    • 5.3 case
  • 6 函数
  • 7 循环
    • 7.1 while
    • 7.2 for
  • 8 shell script的追踪与Debug

1 什么是Shell Scipt

使用指令和基本程序设计结构写成的程序,可以完成复杂的处理流程

1.1 程序书写

#!/bin/bash
# Program:
#       This program shows "Hello Wrold" in your screen.
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATH
echo -e "Hello World!\a\n"
exit 0
  • 第一行 #!/bin/bash 说明使用的shell类型,不同shell语法可能不同,所以要说明使用的是哪种shell
  • 其它#开始的表示注释,注释一般需要说明
    • 程序功能
    • 版本历史
    • 作者及联系方式
  • 设置好PATH变量,以便直接可以调用相应路径下的命令
  • 程序主体部分
  • exit 0 表示程序执行成功,向环境返回0

1.2 程序执行

  • bash $bash sh01.sh #如果用sh sh01.sh而sh又不是指向bash,那么sh01.sh内的语法就会不一致,因为用 #sh去解释了bash语法写的shell script,针对这个程序,如果 #$type sh #得到sh is hashed (/bin/sh) #那么会输出-e Hello world!,而非Hello world!
  • $./xxx.sh $chmod +x sh01.sh $./sh01.sh
  • source $ source sh01.sh

注:用bash和用source的不同在于,用bash执行时,shell script其实是在在父程序bash下新建了一个 bash子程序,这个子程序中执行,当程序执行完后,shell script里定义的变量都会随子程序的结束而消失, 而用source执行时,是在父程序bash中执行,shell script里定义的变量都还在。

2 简单Shell练习

2.1 例1 接收用户输入

# !/bin/bash
# Program:
#       This program is used to read user's input 
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATH
read -p "Your first name:" firstname # tell user to input
read -p "Your last name:" lastname # tell user to input
echo -e "\nYour full name: $firstname $lastname"
exit 0
$ bash sh02.sh
Your first name:Minix
Your last name:007Your full name: Minix 007

2.2 例2 按日期建立相似名字的文件

# !/bin/bash
# Program:
#       This program is used to create files according to date
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATH# Get filename from user
echo -e "I will use 'touch' to create three files."
read -p "Please input your filename:" tmpfilename# Prevent the user input [Enter]
# Check whether filename exists or not
filename=${tmpfilename:-"filename"}# Get the final filename according to date
date1=$(date --date='2 days ago' +%Y%m%d) # date of 2 days ago
date2=$(date --date='1 days ago' +%Y%m%d) # date of yesterday
date3=$(date +%Y%m%d) # date of today
filename1=${filename}${date1}
filename2=${filename}${date2}
filename3=${filename}${date3}# Create file
touch "$filename1"
touch "$filename2"
touch "$filename3"exit 0
$ bash sh03.sh
I will use 'touch' to create three files.
Please input your filename:WhoKnows
$ ls W*
WhoKnows20130201  WhoKnows20130202  WhoKnows20130203

3 判断式

3.1 测试文件是否存在

test -e filename会根据filename是否存在返回0或1,再交由echo显示结果

$ test -e sh01.sh  && echo "Exists" || echo "Not exists"
Exists
$ test -e sh0x.sh  && echo "Exists" || echo "Not exists"
Not exists

3.2 test常用选项

3.2.1 文件类型

  • -e file :file是否存在
  • -f file :file是否存在且为文件
  • -d file :file是否存在且为目录

3.2.2 权限

  • -r file :file是否有读的权限

3.2.3 文件新旧比较

  • -nt file1 file2 : file1 是否比 file2新

3.2.4 整数,字符串,多重条件判断

  • -z string: string是否为空

例:输出指定文件类型及属性

# !/bin/bash
# Program:
#       This program is used to output type and permission of the target file
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATH# Get filename from user
echo -e "Input name of the file that you want to check.\n"
read -p "Filename:" filename
test -z $filename && echo "You must input a filename." && exit 0# Check whether the file exists or not
test ! -e $filename && echo "The file '$filename' DO NOT exists" && exit 0# Check type and permission of the file
test -f $filename && filetype="regular file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"# Output result
echo "The filename:$filename is a $filetype"
echo "And Permissions are :$perm"exit 0
$ bash sh04.sh
Input name of the file that you want to check.Filename:sh01.sh
The filename:sh01.sh is a regular file
And Permissions are :readable writable executable

3.3 使用[]判断

  • 测试文件是否存在
$ [ -e "sh01.sh" ] ; echo $?
0
$ [ -e "sh0x.sh" ] ; echo $?
1
  • 注意[]内空格必须有
  • 这种方法和test的test -e "sho1.sh" ; echo $? 是一致的

4 Shell Script 参数

# !/bin/bash
# Program:
#       This program is used to ouput parameter of the shell script
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHecho "The script's name is ==> $0"
echo "Total parameter number is ==> $#"# Check whether number of the parameter is less than 2
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2.Stop here." && exit 0echo "The whole parameter is ==> '$@'"
echo "The first parameter is ==> $1"
echo "The first parameter is ==> $2"exit 0
$ bash sh05.sh 1a 2b 3c 4d
The script's name is ==> sh05.sh
Total parameter number is ==> 4
The whole parameter is ==> '1a 2b 3c 4d'
The first parameter is ==> 1a
The first parameter is ==> 2b

注:从以上程序可以看出与参数有关的预设变量如何表示

5 条件表达式

5.1 if 结构

# !/bin/bash
# Program:
#       This program is used to show if else expression
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHread -p "Please input [Y/N]" choice
if [ "$choice" == "Y" ] || [ "$choice" == "y" ];thenecho "OK, continue"exit 0
fi
if [ "$choice" == "N" ] || [ "$choice" == "n" ];thenecho "Oh, interupt"exit 0
fiexit 0
$ bash sh06.sh
Please input [Y/N]y
OK, continue
$ bash sh06.sh
Please input [Y/N]n
Oh, interupt

5.2 if else 结构

# !/bin/bash
# Program:
#       This program is used to show if else expression
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHread -p "Please input [Y/N]" choice
if [ "$choice" == "Y" ] || [ "$choice" == "y" ];thenecho "OK, continue"exit 0
elif [ "$choice" == "N" ] || [ "$choice" == "n" ];thenecho "Oh, interupt"exit 0
elseecho "Input [Y/N]"
fiexit 0

5.3 case

# !/bin/bash
# Program:
#       This program is used to show case expression
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHread -p "Tell me your choice:[1-3]=>" choice
case $choice in"1")echo "Your choice is ONE";;"2")echo "Your choice is TWO";;"3")echo "Your choice is THREE";;
esacexit 0
$ bash sh08.sh
Tell me your choice:[1-3]=>2
Your choice is TWO
$ bash sh08.sh
Tell me your choice:[1-3]=>1
Your choice is ONE
$ bash sh08.sh
Tell me your choice:[1-3]=>3
Your choice is THREE

6 函数

# !/bin/bash
# Program:
#       This program is used to test function
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHfunction myprint(){echo -n "Your choice is "
}read -p "Tell me your choice:[1-3]=>" choice
case $choice in"1")myprint;echo "ONE";;"2")myprint;echo "TWO";;"3")myprint;echo "THREE";;
esacexit 0
$ bash sh09.sh 
Tell me your choice:[1-3]=>1
Your choice is ONE
$ bash sh09.sh 
Tell me your choice:[1-3]=>2
Your choice is TWO
$ bash sh09.sh 
Tell me your choice:[1-3]=>3
Your choice is THREE

7 循环

7.1 while

# !/bin/bash
# Program:
#       This program shows while expression
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHwhile [ "$choice" != "yes" ]
doread -p "Give your choice [yes/no]:" choice
doneexit 0
$ bash sh10.sh 
Give your choice [yes/no]:no
Give your choice [yes/no]:no
Give your choice [yes/no]:nx
Give your choice [yes/no]:yes

7.2 for

# !/bin/bash
# Program:
#       This program is used to demo for expression
# History:
# 2013/2/3 on_1y First releasePATH=$PATH
export PATHfor choice in 1 2 3
doecho "your choice is $choice"
doneexit 0
$ bash sh11.sh
your choice is 1
your choice is 2
your choice is 3

8 shell script的追踪与Debug

  • sh -n xx.sh # 语法检查
  • sh -x xx.sh # 列出xx.sh的执行过程

转载于:https://www.cnblogs.com/Iambda/archive/2013/02/15/3933507.html

相关文章:

django admin组件

admin实例 from django.contrib import admin from app01 import models from django.utils.safestring import mark_safe # Register your models here. class UserInfoConfig(admin.ModelAdmin):# 自定义显示的东西def xxx(self):return mark_safe(<a href>xx</a>…

C语言网络编程:close或者shutdown断开通信连接

文章目录前言close函数介绍shutdown函数介绍前言 这里在主要通过实例进行描述close函数在网络编程中的使用 TCP编程模型中客户端或者服务器只要主动通过close发起断开连接的请求&#xff0c;则通信连接可以中断。 可以通过在主进程中抓取通信端的断开信号&#xff0c;比如SIGI…

Await, and UI, and deadlocks! Oh my!

It’s been awesome seeing the level of interest developers have had for the Async CTP and how much usage it’s getting. Of course, with any new technology there are bound to be some hiccups. One issue I’ve seen arise now multiple times is developers acc…

传智播客java基础的习题_传智播客java基础班(集合与IO)阶段测试题

本帖最后由 zhaodecang 于 2016-6-8 19:38 编辑单选题&#xff1a;(每道题目2分)1. ArrayList类的底层数据结构是( )a) 数组结构b) 链表结构 c) 哈希表结构 d) 红黑树结构2. LinkedList类的特点是( )a) 查询快b) 增删快c) 元素不重复 d) 元素自然排序3. Vector类的特点…

$@ 与 $* 差在哪?

$ 与 $* 差在哪&#xff1f; 要说 $ 与 $* 之前&#xff0c;需得先从 shell script 的 positional parameter 谈起...我们都已经知道变量(variable)是如何定义及替换的&#xff0c;这个不用再多讲了。但是&#xff0c;我们还需要知道有些变量是 shell 内定的&#xff0c;且其名…

[源码和文档分享]基于Netty和WebSocket的Web聊天室

一、背景 伴随着Internet的发展与宽带技术的普及&#xff0c;人们可以通过Internet交换动态数据&#xff0c;展示新产品&#xff0c;与人进行沟通并进行电子商务贸易。作为构成网站的重要组成部分&#xff0c;留言管理系统为人们的交流提供了一个崭新的平台。同时&#xff0c;聊…

t-tcpdump

文章目录写入和读取数据包抓取数据包抓取指定网卡流量指定数据的输出格式数据包抓取的方向输出信息的详细程度的可控选项抓取指定协议的数据包表达式介绍逻辑连接符的使用type的确定写入和读取数据包 在工作或者生活中的网络故障排除时最有力的方式就是抓包分析网络状况&#…

java jdk 8u111_8u111-jdk-alpine在java开发中的NullPointerException错误解决方案

问题描述在部署一个验证码服务的容器服务时遇到了一个空指针错误&#xff0c;错误代码为&#xff1a;java.lang.NullPointerExceptionat sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguratio…

sprintf函数做什么用?

sprintf函数原型为 int sprintf(char *str, const char *format, ...)。作用是格式化字符串&#xff0c;具体功能如下所示&#xff1a; &#xff08;1&#xff09;将数字变量转换为字符串。 &#xff08;2&#xff09;得到整型变量的16进制和8进制字符串。 &#xff08;3&#…

Yii学习笔记【3】

加载控制器及其方法&#xff1a; 根据route信息&#xff0c;获得当前控制器| 初始化当前控制器&#xff0c;CController::init()&#xff0c;默认为空| 执行当前控制器&#xff0c;CController::run()||----> 创建action&#xff0c;为空则默认为index|得到CInlineAction的实…

验证码相似问题

产生随机验证码时&#xff0c;类似数字1和小写字母l经常容易让人混淆分不清楚&#xff0c; 因此&#xff0c;产生随机验证码时应避免此情况 1&#xff08;一&#xff09;、l&#xff08;哎哦&#xff09;、I &#xff08;哎&#xff09;中三个任意两个或者全部不可同时存在 0&a…

C语言网络编程:accept函数详解

文章目录前言函数描述代码实例如何得到客户端的IP 和 端口号前言 当使用tcp服务器使用socket创建通信文件描述符&#xff0c;bind绑定了文件描述符&#xff0c;服务器ip和端口号&#xff0c;listen将服务器端的主动描述符转为被动描述符进行监听之后&#xff0c;接口accept通过…

java 声明静态类_java静态类声明--java类可以声明为static吗

为了理解static关键字在类声明中的使用&#xff0c;首先我们需要了解类声明。有两种类&#xff0c;一种是top-level class&#xff1b;一种是inner class。Top-level classestop-level class可以被声明为包成员&#xff0c;每一个top-level类对应于一个文件名与类名相同的java文…

单元测试资料汇总

从安装到配置 首先到官网http://www.nunit.org/下载如下图的资料&#xff0c;安装NUnit-2.6.1.msi包。 然后挂在VS2010外部工具这个地方来使用&#xff0c;工具—>外部工具—>添加—>标题&#xff1a;Nunit—>命令&#xff1a;安装路径—>确定。 然后打开Nunit&…

rhel5+nis+autofs+nfs

创建NIS服务器用户&#xff0c;用于客户端登陆 NIS服务器相关包&#xff1a;ypserv、ypbind(在RHEL5中默认已安装)、yp-tools(在RHEL5中默认已安装)。 运行nisdomainname test.com并把加入到如下位置 设置NIS服务器的域名 在NIS环境中将以NIS服务器上的所有用户用于NIS环境中所…

Beta冲刺 (1/7)

Part.1 开篇 队名&#xff1a;彳艮彳亍团队 组长博客&#xff1a;戳我进入 作业博客&#xff1a;班级博客本次作业的链接 Part.2 成员汇报 组员1&#xff08;组长&#xff09;柯奇豪 过去两天完成了哪些任务 熟悉并编写小程序的自定义控件展示GitHub当日代码/文档签入记录接下来…

C语言网络编程:listen函数详解

文章目录前言函数描述代码实例TCP服务器为什么调用listen前言 根据TCP编程模型中我们可以看到之前的socket和bind接口是tcp服务器在为接收客户端的链接做准备&#xff0c;保证tcp的面向字节流&#xff0c;面向连接的可靠通信服务正常进行。接下来的listen端口则为我们进行三次…

MVC页面加载速度优化小记

前言&#xff1a;最近做一个地图展示页面&#xff0c;业务初期没什么问题&#xff0c;运行一阵后报错&#xff1a; Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLeng…

java生成函数excel_java实现在excel中创建及读取公式

操作excel表格用公式来处理数据时&#xff0c;可通过创建公式来运算数据&#xff0c;或通过读取公式来获取数据信息来源。这里使用了java类库(Free Spire.XLS for Java 免费版)获取文件包后&#xff0c;解压&#xff0c;将lib文件夹下的jar文件导入Java程序。如图&#xff1a;(…

实战:使用TCP/IP筛选保护服务器安全

使用TCP/IP筛选保护服务器安全 对于部署在Internet的服务器&#xff0c;安全是必须要考虑的事情。为了降低服务器受***的危险&#xff0c;停止不必要的服务或在本地连接的TCP/IP属性中只打开必要的端口。 如图2-127所示&#xff0c;实验环境为Server的IP地址192.168.1.200&…

python中的协程(二)

协程 1、协程&#xff1a; 单线程实现并发 在应用程序里控制多个任务的切换保存状态 优点&#xff1a; 应用程序级别速度要远远高于操作系统的切换 缺点&#xff1a; 多个任务一旦有一个阻塞没有切&#xff0c;整个线程都阻塞在原地&#xff0c;该线程内的其他的任务都不能执行…

C语言网络编程:bind函数详解

文章目录函数功能函数头文件函数使用函数参数函数举例为什么需要bind函数服务器如何知道客户端的ip和端口号htons函数htons兄弟函数htonl,ntohs,ntohl为什么要进行端口的大小端序的转换inet_addr函数函数功能 bind API能够将套接字文件描述符、端口号和ip绑定到一起 注意&…

java flex 图片上传_flex上传图片到java服务器

今天弄flex上传图片到java&#xff0c;现在弄成功&#xff0c;中间也经常一点小波折&#xff0c;现记录一下。重点在java侧的实现。flex侧&#xff1a;文件上载到在url参数中传递的URL。该URL必须是配置为接受上载的服务器脚本。Flash Player使用HTTP POST方法上载文件。处理上…

开发者怎么样做到盈利

开发者如何赚钱? 不可回避的一点就是&#xff0c;开发者的产品要有足够好的用户体验。假设你会做手机游戏&#xff0c;那么把手游做好了之后用户的粘性很大&#xff0c;如果你做应用&#xff0c;那么你的应用下载会对用户产生有价值的东西。 其实如果你的产品真的有价值&#…

如何在Windows Azure VM上的SQL Server和Windows Azure SQL Database两者中做出选择

作者信息&#xff1a;本篇文章是由SQL Server Cloud Infrastructure Team的 Madhan Arumugam 和 Guy Bowerman共同著作。 简介 把SQL 数据托管在哪里&#xff0c;Windows Azure 为您提供了两个选择&#xff0c;VM上的SQL Server&#xff08;以下简称 SQL/VM&#xff09;和 Wind…

C语言网络编程:socket函数

函数描述 头文件 <sys/types.h> <sys/socket.h> 函数使用int socket(int domain, int type, int protocol); 函数功能&#xff1a;创建一个通信的终点&#xff0c;并返回一个文件描述符来代表通信的终点 函数参数&#xff1a; a. domain 代编当前创建的socket文…

python excel web_使用python在WEB页面上生成EXCEL文件

近日写的一个程序需要在WEB服务器上生成EXCEL文件供用户下载&#xff0c;研究了一下找到了以下比较可行的实现方案&#xff0c;下面以web.py为例&#xff0c;把相关代码贴出来供大家参考&#xff1a;首先需要下载生成EXCEL的模块&#xff0c;推荐使用xlwtimport xlwtimport Str…

dateTimePicker编辑状态下,取值不正确的问题

当对dateTimePicker进行编辑&#xff0c;回车&#xff0c;调用函数处理dateTimePicker的value值时&#xff0c;其取值结果是你编辑之前的值&#xff0c;而不是你编辑后的值&#xff0c;虽然dateTimePicker.text的值是编辑后的值&#xff0c;但使用起来不方便&#xff0c;因此暂…

RMAN Backups

oracle 主要的备份工具 RMAN 其中&#xff0c;open database backup, 不需要把数据库设置成backup状态, RMAN reads a block until a consistent read is obtained. 看来备份比较重要的三种文件分别是, data file, control file, archivelog file. Types of Recovery Manager B…

异步使用委托delegate --- BeginInvoke和EndInvoke方法

当我们定义一个委托的时候&#xff0c;一般语言运行时会自动帮委托定义BeginInvoke 和 EndInvoke两个方法&#xff0c;这两个方法的作用是可以异步调用委托。 方法BeginInvoke有两个参数&#xff1a; AsyncCallBack&#xff1a;回调函数&#xff0c;是一个委托&#xff0c;没有…