1. Shell脚本
1.1 什么是Shell脚本
-
Shell脚本是利用shell的功能所写的一个program,这个程序是使用纯文本文件,将一些shell的语法和命令整合起来,搭配正则表达式、管道命令与数据重定向,达到我们的目的
-
书写脚本前的说明
- 命令是从上而下、从左到右的分析与执行
- 命令、选项与参数间的多个空格都会被忽略
- 空白行也会被忽略,由Tab按键所产生的空白同样是空格键
- 读到一个Enter符号,就尝试该行(该串)命令
- #可作为注释,任何加在#后面的数据将全部被视为注释文字
- shell.sh脚本文件必须具备可读与可执行权限
- 以bash程序来执行,[bash shell.sh] [sh shell.sh]
-
无名氏的第一个脚本文件
#!/bin/bash # Program: # This program shows "hello world!" in your screen. # History: # 2021/5/10 Mac First release echo -e "hello world! \a" exit 0
-
保持编写脚本的好习惯
随着学习深入,编写的脚本代码增多、功能变复杂,应当保持在脚本头部写好一些信息
- 脚本的功能
- 脚本的版本信息
- 脚本的作者与联系方式
- 脚本的版权声明方式
- 脚本内特殊的命令使用绝对路径来执行
- 预先声明并设置运行时需要的环境变量
1.2 简单的shell脚本练习
-
交互式脚本
#!/bin/bash # Program: # User input his first name and last name, program shows his full name. # History: # 2021/5/10 Mac First release read -p "Please input your first name: " firstname #提示用户输入 read -p "Please input your last name: " lastname #提示用户输入 echo -e "\nYour full name is: ${firstname} ${lastname}" #屏幕输出结果
-
随日期变化
#!/bin/bash # Program: # Program creates one file, which named by user's input and date command. # History: # 2021/5/10 Mac First release # 让用户输入文件名称,并取fileuser变量 read -p "Please input your filename: " fileuser # 对fileuser变量判空, 为空则设置filename为filename,不为空则使用用户输入的值 filename=${fileuser:-"filename"} # 使用date命令获取当前时间 date=$(date +%Y%m%d) # 组装文件名 file=${filename}${date} # 创建文件 touch "${file}"
-
数值运算
#!/bin/bash # Program: # User input two numbers, program will cross these two numbers. # History: # 2021/5/10 Mac First release echo -e "input 2 numbers, I will multiply them! \n" read -p "first number: " firstnu read -p "second number: " secondnu total=$((${firstnu}*${secondnu})) echo -e "\nThe result of ${firstnu} x ${secondnu} is ==> ${total}"