您的位置:首页 > 运维架构 > Shell

shell简单编程

2016-06-10 13:17 489 查看
基础

$0 表示shell文件本身的文件名.
$1,$2,$3 指向每个参数
$#表示参数的个数
$*/$@表示所有参数的整体
$x 用于取变量x的值
$$ 进程id.

shift移动一个参数。

':',相当于nop,是一条空命令,while[ true ] : --> 死循环.

';',用于在一行分隔命令,if[ condition ] ; then

export x=100 ;导出一个环境变量x.

命令替换:使用`A`或者$(A),将$(A)的操作结果,传给下一个调用者.
eg cat $(ls) > merge  // cat `ls` > merge

exit val ;结束当前脚本并以val作为返回值.

$? ; 返回上一条命令的执行结果.

test 用于shell条件判断,if test 2 -eq 2 //不需要[]
----用于测试文件信息是否正确-----
test -f fn ;fn是否为为文件
test -d fn ;fn是否为文件夹
test -r/w/x ;当前用户对该文件是否有读/写/执行权限
----value--------------
test "sfas" == "afds"
test "sf" -eq "afas"
test 12 -lt 13

&& 和 || 就是那个意思没错!!!!!


标准shell变量(内置)

date --> 日期
pwd --> 当前绝对工作路径


赋值与循环分支

let i=$x+$y,为整数操作赋值,所以必须有两个以上操作数.当只有一个操作数时使用,i=$x.

#!/bin/bash
echo "please input num:"
read num
echo "the num is $num"
#声明变量,不能有空格
sum=0
i=0
# while循环,需要留出空格
while [ $num -gt $i ]
do
let mo=$i%2
# 开始条件需要留出空格
# then,else 要单独留出空行
if [ $mo -eq 0 ]
then
3 赋值不能有空格
let sum=$sum+$i
elif [ $mo -eq 2 ]
then
echo "ll"
else
touch $i
tar cvf - `find . -mtime -1 -type f -print` > x.tar
# 结束条件
fi
let i=$i+1
# 结束循环
done
echo "the sum is $sum"


for循环以及数组

#!bin/bash
echo "my student number is :1133710513, my name is zhiwei huang"
city[1]=Beijing
city[2]=Shanghai
city[3]=Wuxi
city[4]=Wenzhou
city[5]=Berkeley
# for z in 1 2 7
for i in ${city[*]}
do
echo $i
done


打印

#!/bin/bash
echo "my student number is :1133710513, my name is zhiwei huang"
i=0
for ((k=0;k<10;k++))
do
for((j=0;j<=k;j++))
do
echo -n "$j "
done
echo " "
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell