shell脚本学习随笔
shell脚本随笔
常用特殊符号
. ---当前目录
.. ---上一级目录
~ ---当前用户的家目录
/ ---根目录
- ---上一次所在的工作目录
* ---任意一个或多个字符
?---一个字符
[]---中括号里任意一个字符
{}---大括号里的任意字符
> ---覆盖重定向
>>---追加重定向
< ---输入重定向
<<---
``---执行反引号中的命令
1---执行正确
2---错误输入
例
把报错重定向到err.txt中(没有xxx.txt)
ls xxx.txt 2>err.txt
shell基本元素
第一行格式 #!/bin/bash
#后为注释
$后为变量
shell例题以及注释
例: 1.拆分文件
#!/bin/bash
cd /tmp
mkdir shell
cd shell
cp /etc/passwd ./
for i in `seq 1 100`; //从1到100循环
do cat /etc/passwd >> ./passwd; //输出重定向
done
split -l 1000 passwd hx //按行拆分
split -b 1024 passwd hh //按文件大小拆分
2. 以日期为名称把磁盘信息写入进去
#!/bin/bash
d=`date +%F` //给d赋值当前日期中的年月日
logfile=$d.log //文件名为变量d.log
df -h>$logfile //把磁盘情况写入变量logfile
3 内存统计
#!/bin/bash
sum=0
for mem in `ps aux|awk '{print $6}'|grep -v 'RSS'`
//ps aux显示进程情况,打印第六行(内存使用量并过滤RSS)
do
sum=$[$sum+$mem]
done
echo “The total memory is $sum”"KB"
echo "The total memory is `expr $sum / 1024`""MB"
4. 大小比较
#!/bin/bash
read -p "Input the first number:" n1
//把屏幕输入结果输入给n1
echo $n1
read -p "Input the second number:" n2
echo $n2
if [ $n1 -gt $n2 ]; //-gt===greater than
-lt===less than
-eq===equal
then echo "the first number is the big one.";
elif [ $n1 -eq $n2 ];
then echo "eq"
else echo "the second number is the big one.";
fi
echo $n1
echo $n2