文档介绍:Linux 操作系统
Shell 脚本编程
主要内容和学习要求
掌握创建 shell 脚本的基本步骤
学会使用条件测试
掌握 if 条件结构与 case 选择结构
掌握 for 循环、while 循环和 until 循环结构
学会 shift 命令的使用
学会 shell 脚本的调试
Shell 脚本
Shell 脚本
如果有一系列你经常使用的Linux命令,你可以把它们存储在一个文件里,shell可以读取这个文件并顺序执行其中的命令,这样的文件被称为脚本文件。shell 脚本按行解释。
Shell 脚本的编写
Shell 脚本是纯文本文件,可以使用任何文本编辑器编写
Shell 作为后缀名
Shell 脚本的执行
chmod +x script_name
./script_name
bash script_name
第一行:指定用哪个程序来编译和执行脚本。
Shell 脚本的格式
#!/bin/bash
可执行语句和 shell 控制结构
注释:以“# ”开头,可独占一行,或跟在语句的后面。
Shell 脚本
#!/bin/sh
#!/bin/csh
一个 shell 脚本通常由一组 Linux 命令、shell 命令、控制结构和注释语句构成。
在脚本中多写注释语句是一个很好的编程习惯
#!/bin/bash
# This is the first Bash shell program
# ScriptName:
echo
echo –e "Hello $LOGNAME, \c"
echo "it's nice talking to you."
echo "Your present working directory is:"
pwd # Show the name of present directory
echo
echo –e "The time is `date +%T`!. \nBye"
echo
bash
chmod +x
./greetings
Shell 脚本举例
echo命令
功能说明:显示文字。
语法:echo [-ne][字符串]
或 echo [--help][--version]
补充说明:echo会将输入的字符串送往标准输出。输出的字符串间以空白字符隔开, 并在最后加上换行号。
-n 不进行换行
-e 若字符串中出现以下字符,则特别加以处理,而不会将它当成一般文字输出\n 换行\b 空格...
参数:
-n 不要在最后自动换行
-e 若字符串中出现以下字符,则特别加以处理,而不会将它当成一般文字输出:
\a 发出警告声;
\b 删除前一个字符;
\c 最后不加上换行符号;
\f 换行但光标仍旧停留在原来的位置;
\n 换行且光标移至行首;
\r 光标移至行首,但不换行;
\t 插入tab;
\v 与\f相同;
\\ 插入\字符;
\nnn 插入nnn(八进制)所代表的ASCII字符;
--help 显示帮助
--version 显示版本信息
#!/bin/bash
# This script is to test the usage of read
# Scriptname:
echo "=== examples for testing read ==="
echo -e "What is your name? \c"
read name
echo "Hello $name"
echo
echo -n "Where do you work? "
read
echo "I guess $REPLY keeps you busy!"
echo
read -p "Enter your job title: "#自动读给REPLY
echo "I thought you might be an $REPLY."
echo
echo "=== End of the script ==="
Shell 脚本举例
read命令
read variable #读取变量给variable
read x y #可同时读取多个变量
read #自动读给REPLY
read –p “Please input: ”
#自动读给REPLY