Shell学习笔记
Shell类似于windows下的批处理bat
Shell功能更加强大,而且已经变成了一门比较强大的编程语言
执行了Shell脚本,就执行了Shell中多个命令
可以做成分发脚本
创建和执行Shell脚本
使用echo命令显示信息
创建变量
使用本地和全局变量
计算表达式
使用if构造执行基于条件的Shell脚本
使用case构造执行基于条件的Shell脚本
Shell脚本可以起为任何名字,也可以没有任何后缀名,但是作为方便一般取名为.sh
可以使用任何编辑器编写Shell脚本
必须在Shell中执行
要注意增加可执行权限 chmod a+x
Shell脚本可以包含注解入口
Echo "Hello!"
# This is a comment line.
Echo "world!"
第二行是注解,将会被shell忽略
变量
创建变量可以在任何时间通过简单的赋值来创建
语法 变量名=变量值
Linux所有变量都被当做字符串
引用变量
Variable1=${variable2}
引用第二个值赋值给第一个variable
从键盘读入值给变量
read 变量名
把终端输入的内容存储到变量名中
本地和全局Shell变量
默认是局部变量,全局变量要使用exprot来特别指定
环境变量
HOME
指代用户HOME主目录
echo $HOME ($变量引用一个变量)
PATH
包含一列用冒号定界的路径名字
搜索可执行文件的路径
PS1
设置shell的提示符
$ PS1="HELLO>" <Enter>
HELLO> New prompt
LOGNAME
获取用户登录名
$ echo "${LOGNAME}"
SHLVL
当前shell的工作level
SHELL
存储了用户的缺省默认shell
Env命令
查看所有环境变量和值
命令替换
echo "The date is `date` " 波浪号下的`
expr命令
用于求值算术表达式
expr 4 + 5 在屏幕上输出9 注意4空格+ 空格 5
算术展开
在$((...))中括一个表达式
小例子
echo "enter number1"
read number1
echo "enter number2"
read number2
sum=$((number1+number2))
echo "the number is $sum"
test 和 [] 命令,获取条件 []注意左右的空格
求值表达式,返回true (0)或false
也可以用于字符串
以及文件测试
if提供循环和判定构造
exit 终止shell并返回到$提示符下
test数值测试
-eq 等于为真
-ne 不等于为真
-gt 大于
-ge 大于等于
-lt 小于
-le 小于等于
字符串测试
= 等于为真
!= 不相等为真
-z 长度为0为真
-n 长度不为0为真
文件测试
-e 文件存在
-r 存在可读
-w 存在可写
-x 存在可执行
-s 存在至少有一个字符
-d 存在且为目录
-f 存在为普通文件
-c 存在字符型特殊文件
-b 存在块特殊文件
-a 并且 -o 或者 ! 非
case...esac
类似switch
read choose
case $choose in
1) echo "wwwwwww";;
2) echo "eeeeeeeeeee";;
3) echo "wwwwrrrrrre";;
*) echo "nonono!";;
esac
while构造
while <条件>
do
<命令(s)>
done
until
for循环
for 变量名 in <list_of_valus>
do
...
done
break和continue
例子
codenum=1000
while [ $codenum -le 1002 ]
do
echo "Enter data!"
echo -n "Employee Name:"
read name
echo -n "Employee Address:"
read address
echo -n "Employee Number:"
read number
echo "$codenum : $name : $address :$number"
((codenum=$codenum+1))
done
控制进程的执行
请求后台处理(&)
$ wc tempfile & //计算tempfile中有多少个字符在后台进行处理
检查后台进程 ps
获得进程号
终止进程 kill +进程号
查看完成一个命令所花的时间
time 命令
$ time find /etc -name "passwd" 2>/dev/null
显示在/etc文件夹下查找名称为passwd的文件所用的时间,把错误信息重定向到
/dev/null上忽略掉
'|' 管道字符
把前面命令的输出作为后面命令的输入
ls -l | more
Demo
#The demo of study Shell!
echo "Please input you name!"
read name
echo "Your name is ${name}"
echo "Input the number!"
read number
if [ $number -ge 80 -a $number -lt 90 ]
then
echo "number is $number and is good!"
elif [ $number -gt 90 ]
then
echo "$number is very good!"
else
echo "$number is not very good!"
fi
要注意
引用变量加$,
[ ]两侧的空格,
case $变量 in
1) ls ;;
2) ls -al;;
*) echo "input error!";;
esac
数学运算都要用双括号括起来
whiel [ ]
do
...
done
其它相关
PATH=$PATH:.
添加当前目录到系统路径下,不用再输入./