Linux学习笔记之一 ---Shell语法(1)
只要在linux下运维或者完成某些功能,都会接触到shell脚本的编写,Shell容易而强大,但是有时候查找语法确是零碎的,特别在天朝下很多都是CTL+C,CTL+V而形成的资料,这里只是记录学习,如有错误,多多包涵和指教。
开始学习吧:
Shell 语法 :
1.变量
Linux是区分大小写的系统;使用变量名前面加上$来访问变量的内容,为变量赋值时,只是需要变量名,变量会根据需要自动创建
-
$salutation=hello
-
$echo $salutation
-
hello
-
$salutation=
"YesDear"
-
$echo $salutation
-
YesDear
1.1 read 命令等待用户输入并且赋值
$read salutation Wiegeht's $echo $salutation Wiegeht's
双引号不会影响变量的替换,单引号和反斜杠不进行变量转换
-
$varTest=
"Test"
-
$echo $varTest
-
Test
-
$echo
"$varTest"
-
Testg
-
$echo
'$varTest'
-
$varTest
-
echo \$varTest
-
$varTest
$0:shell脚本的名字
$#传给给脚本的参数个数
2.条件
test或[命令
eg1:检查一个文件是否存在
-
if test -f fred.c
-
then
-
....
-
fi
-
or
-
if[ test -f fred.c]; then
-
....
-
fi
ps:[ A ]和检查内容A之间需要空格,如果想if和then同一行,那么需要分号
2.1字符串比较
str1 = str2 相等为真
str2 != str2 不相等为真
-n str1 不为空为真
-z str1 为空为真
2.2数字比较
A -eq B 相等为真
A -ne B 不相等为真
A -gt B A>B
A -ge B A>=B
A -lt B A<B
A -le B A<=B
2.3文件条件测试
-d file 为目录为真
-e file 存在为真,尽量使用-f
-f file 存在为真
-g file 如果文件的set-group-id位被设置则为真
-r file 可读为真
-s file 大小不为0为真
-u file 如果文件的set-user-id位被设置则为真
-w file可写为真
-x file可执行为真
2.4控制结构
(1).if语句
if condition
then
statements
else
statements
fi
(2).elif语句
-
#!/bin/sh
-
echo
"Ii't morning? Please anser yes or no"
-
read timeofday
-
-
-
if[
"$timeofday"=
"yes" ]
-
then
-
echo
"Goodmorning"
-
-
elif [
"$timeofday"=
"no" ];then
-
echo
"Goodafternoon"
-
else
-
echo
"Sorry,$timeofday not recognized,Enter yes or no"
-
exit1
-
fi
-
-
exit0
本次语法笔记结束,下次继续shell语法(2)