第一个Shell程序example.sh:
#!/bin/bash
echo "Our first example"
echo #empty line
echo "We are currently in the following directory"
pwd
echo
echo "This directory contains the following files"
ls
#为单行注释
#!跟shell命令的完全路径,显示后期命令以哪种shell执行
shell程序的创建步骤:
1.创建Shell文件,以.sh结尾。
gedit example.sh
2.修改文件的权限
chmod u+x example.sh
3.执行
方法一:直接执行
./example.sh
方法二:使用bash执行
bash example.sh
方法三:使用绝对路径执行,在当前目录下输入pwd获得该路径
/home/hadoop/test/example.sh
执行结果
shell变量
shell变量分为临时变量(用户自定义变量),永久变量(环境变量)
变量赋值,等号左右不要加空格,如
A=aaa
NAME="Li Ming"
使用变量时要在变量前面加上$符号
echo $A
echo $NAME
查看所有变量输入:set
单引号和双引号的区别:单引号之间的内容原封不动的输出,双引号取消空格作用,特殊符号的含义保留,如:
删除变量使用unset
unset A
位置变量
位置变量以$N表示,N从0开始,0,1,2,……,如:
./example.sh file1 file2 file3
$0指example.sh,$1指file1,$2指file2,以此类推
特殊变量
$* 程序所有参数
$# 参数个数
$$ 程序的pID
$! 执行上一个后台程序的pID
$? 执行上一个指令的返回值
举例:
#!/bin/bash
echo "$* 该程序所有参数"
echo "$# 该程序所有参数个数"
touch /home/hadoop/test/a.txt
echo "$$ 程序的pID"
touch /home/hadoop/test/b.txt &
echo "$! 执行上一个后台指令的pID"
echo "$$ 程序的pID"
结果:
read命令
从键盘中读取数据
expr命令
做算数运算,乘法需要在*前加转义 \
举例:(可以有负数,除不尽的抹去小数部分)
#!/bin/bash
read num1 num2
expr $num1 + $num2
expr $num1 - $num2
expr $num1 \* $num2
expr $num1 / $num2
结果: