linux预习2 shell
1.标准文件描述符:0标准输入,1标准输出,2标准错误输出
2.输出重定向(eg:ls -1 > xxx.txt):
'>'遇到已经存在文件会覆盖(set -c防止覆盖)
‘>>’将输出附加到文件中
‘>&’结合两个输出(eg:kill -1 1234 >xxx.txt 2>&1)将标准输出重定向到xxx.txt,再将标准错误输出重定向到与标准输出相同的地方
3.管道:‘|’用于连接进程,sort命令用于对输出进行排序,more分页输出
eg:ps | sort | more
4.shell程序设计:交互式程序/创建脚本
5.可运行脚本:chmod +x xxx(用./xxx运行避免运行同名的命令)
6.chmod 755 /usr/local/bin/xxx (7 5 5分别对应onwer,group,other,二进制后对应 读,写,执行)
7.变量:使用前一般不需要申明,$"xx"输出xx的值,$‘xx’输出的是xx,\$ss的输出是:$ss
eg:
salutation=Hello echo $salutation Hello salutation=”Yes Dear” //字符串有空格时必须加“ ” echo $salutation Yes Dear
8.环境变量:
$HOME 当前用户的家目录
$PATH 以冒号分隔,用以搜索命令的目录列表
$PS1 命令提示符,通常是$字符
$PS2 二级提示符,通常是>字符
$IFS 输入域分隔符,空格,制表,换行
$0 shell脚本的名字
$# 传递给脚本的参数的个数
$$ shell脚本的进程号
参数变量:
$1,$2..... 脚本程序的参数
$* 在一个变量中列出所有的参数,各个参数之间用环境变量IFs的第一个字符分隔
$@ 分隔参数且不通过IFS
9.条件语句:test / []
eg:
if test -f xxx.c #也可以写成:if [ -f xxx.c ] , []和内容之间有空格
then
.....
elif
.....
else
...
fi
10.条件类型:
- 字符串:=,!= , -n(非空为真) ,-z(空为真)
- 算数: -eq(相等) -ne(不相等) -gt(大于) -ge(大于等于) -lt(小于) -le(小于等于)
- 文件:-r,-w,-x(读,写,执行),-f(存在)-s(大小不为0)-d(文件是个目录)
11.for循环:
eg:
#!/bin/sh
for file in $(ls l*.sh);do
echo $file
done
exit 0
12.while循环
eg:
#!/bin/sh
read trythis
while [ "$trythis" != "password" ];do
echo "try again"
done
exit 0
13.case
eg:
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
case “$timeofday” in
yes) echo “Good Morning”
echo "hello";;
no ) echo “Good Afternoon”;;
y ) echo “Good Morning”;;#也可以写成 yes | y ) echo “Good Morning”;;
n ) echo “Good Afternoon”;;
* ) echo “Sorry, answer not recognized”;;
esac
exit 0
14.函数:
eg:
#!/bin/sh
yes_or_no(){
echo "is your name $* ?"
while true
do
echo -n "Enter yes or no:"
read x
case "$x" in
yes ) return 0;;
no) return 1::
* )echo "answer yes or no"
esac
done
}
echo "Original parameters are $*"
if yes_or_no "$1"
then
echo "hi $1 ,nice name"
else
echo"never mind"
fi
exit 0
15.命令:
1.break 跳出循环
2. : 相当于true
3.continue
4. . 命令
5. echo
6.eval (类似于多了一个$)
eg:
foo=10
x=foo
eval y = '$'$x
echo $y #输出结果为10
7.exec 将当前shell替换掉
8.exit
9.expr 算术
10.set 设置参数, unset 删除参数
11.shift 参数左移一个($2变成$1)
12.find命令 在系统中搜索文件 eg:-exec command
13.grep 在文件中搜索字符串 默认输出匹配行内容 -c 输出匹配行的数目,-i 忽略大小写, -v 对匹配模式取反。
16.命令的执行:
算术扩展:$((......))eg:x=$(($x + 1))
参数扩展:数组:{#x}给出x的长度,{x%y}从x的尾部找,删除与y匹配的最小部分,然后返回;{x##y}从偷找,删最长。
#!/bin/sh
for i in 1 2
do
echo ${i}_file #通过{}实现
done
17.here文档:以<<开始后接特殊的字符序列并以此序列结束eg:
cat <<!FUNKY!
hello
!FUNKY!
浙公网安备 33010602011771号