学习 Shell Scripts
什么是Shell Scripts
shell script (程序化脚本)是利用 shell 的功能所写的一个『程序 (program)』,这个程序是使用纯文字档,将一些 shell 的语法与命令(含外部命令)写在里面, 搭配正规表示法、管线命令与数据流重导向等功能,以达到我们所想要的处理目的。shell script 可以简单的被看成是批量档, 也可以被说成是一个程序语言,且这个程序语言由於都是利用 shell 与相关工具命令, 所以不需要编译即可运行。
script 的撰写与运行
行这个文件可以有底下几个方法:
直接命令下达: shell.sh 文件必须要具备可读与可运行 (rx) 的权限,然后:
- 绝对路径:使用 /home/dmtsai/shell.sh 来下达命令;
- 相对路径:假设工作目录在 /home/dmtsai/ ,则使用 ./shell.sh 来运行
- 变量『PATH』功能:将 shell.sh 放在 PATH 指定的目录内,例如: ~/bin/
以 bash 程序来运行:透过『 bash shell.sh 』或『 sh shell.sh 』来运行
[root@www ~]# mkdir scripts; cd scripts
[root@www scripts]# vi sh01.sh
#!/bin/bash
# Program:
# This program shows "Hello World!" in your screen.
# History:
# 2005/08/23 VBird 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
简单范例
对谈式脚本:变量内容由使用者决定
[root@www scripts]# vi sh02.sh #!/bin/bash # Program: # User inputs his first name and last name. Program shows his full name. # History: # 2005/08/23 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH read -p "Please input your first name: " firstname # 提示使用者输入 read -p "Please input your last name: " lastname # 提示使用者输入 echo -e "\nYour full name is: $firstname $lastname" # 结果由萤幕输出- 数值运算:简单的加减乘除
[root@www scripts]# vi sh04.sh #!/bin/bash # Program: # User inputs 2 integer numbers; program will cross these two numbers. # History: # 2005/08/23 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH echo -e "You SHOULD input 2 numbers, I will cross them! \n" read -p "first number: " firstnu read -p "second number: " secnu total=$(($firstnu*$secnu)) echo -e "\nThe result of $firstnu x $secnu is ==> $total"
script 的运行方式差异 (source, sh script, ./script)
利用直接运行的方式来运行 script
[root@www scripts]# echo $firstname $lastname <==确认了,这两个变量并不存在喔! [root@www scripts]# sh sh02.sh Please input your first name: VBird <==这个名字是鸟哥自己输入的 Please input your last name: Tsai Your full name is: VBird Tsai <==看吧!在 script 运行中,这两个变量有生效 [root@www scripts]# echo $firstname $lastname <==事实上,这两个变量在父程序的 bash 中还是不存在的!『当子程序完成后,在子程序内的各项变量或动作将会结束而不会传回到父程序中』
利用 source 来运行脚本:在父程序中运行
[root@www scripts]# source sh02.sh Please input your first name: VBird Please input your last name: Tsai Your full name is: VBird Tsai [root@www scripts]# echo $firstname $lastname VBird Tsai <==嘿嘿!有数据产生喔!