Shell Script
$ vim showname.sh
#!/bin/bash
# Program:
# User inputs his first name and last name. Program shows his full name.
# History:
# 2015/07/16 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}" # 结果由屏幕输出
exit 0
$ sh showname.sh #开始执行脚本
以『#!/bin/bash 』来宣告这个文件内的语法使用bash 的语法;
第二行#为注释,用于描述该文件的简介和历史变更记录;
需要导入环境变量;
[exit 0]定义回传值给系统,也可以用其他非零的值定义错误码。
整数运算举例:
var=$((运算内容))
total=$((${firstnu}*${secnu}))
小数运算举例:
使用bc指令
$ echo "123.123*55.9" | bc
bash子程序中执行示例(sh):
$sh showname.sh
bash父程序中执行示例(source):
$source showname.sh
检测系统上面某些文件或者是相关的属性(test):
$ test -e /AABB && echo "exist" || echo "Not exist"
Not exist
判断符号([ ]):
举例来说,如果我想要知道 ${HOME} 这个变量是否为空
$ [ -z "${HOME}" ] ; echo $?
$ [ “${name}” == "VBird" ]
要注意中括号的两端需要有空格符来分隔
第二行要注意左边变量需要用双引号括起来
带参数的命令,脚本内获取参数值,举例:
$ vim how_paras.sh
#!/bin/bash
# Program:
# Program shows the script name, parameters...
# History:
# 2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo "The script name is ==> ${0}"
echo "Total parameter number is ==> $#"
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 0
echo "Your whole parameter is ==> '$@'"
echo "The 1st parameter ==> ${1}"
echo "The 2nd parameter ==> ${2}"
$ sh how_paras.sh theone haha quot
The script name is ==> how_paras.sh <==文件名
Total parameter number is ==> 3 <==果然有三个参数
Your whole parameter is ==> 'theone haha quot' <==参数的内容全部
The 1st parameter ==> theone <==第一个参数
The 2nd parameter ==> haha <==第二个参数