shell脚本demo

数组定义mytest=(hello world)
echo ${mytest[1]}输出world
echo ${mytest[*]} hello world
mytest[1]=nihao变为hello nihao
删除 unset mytest[1]
删除全部 unste mytest
#!bin/bash通知shell以bash/shell来执行程序

echo命令可以使用单引号和双引号来将文本字符串圈起来, 如果在文本字符串用到他们的话,要在文本中使用其中一个引号
> echo "hello 'world'"
hello 'world'
> echo 'hello "world"'
hello "world"
同一行显示一个字符串作为命令输出[两边空格]
echo -n " the time and date are "
输入重定向
wc <123.txt
     206     614   41406
内联输入重定向是双小于号<<[必须指定一个文本标记来划分数据的开始和结尾]
 wc <<EOF
> test string 1
> test string 2
> test string 3
> EOF
3       9      42
数学运算
 expr 1 + 5[中间空格]
 6
 expr 1 * 5
expr: syntax error

 expr 1 \* 5
5
 var1=10
 var2=20
 var3=`expr var2 / $va1`
 使用方括号计算只支持整数计算
 var=$[1 + 5]
 echo $var
 6
 var1=$[$var * 2]
 12
 浮点解决方案
 bc
 scale=4【设置四位浮点数】
 
scale=4
3.44/5
.6880
脚本中使用bc计算
var=` echo "scale=4; 3.44/5"|bc`
查看状态吗$?

if语句
if ls -trl *
then
command
else
command
fi

if [ condition ]条件可以是数值比较,字符串比较,文件比较
then
command
else
command
fi


数值比较-eq相等,-ge大于等于,-gt大于,-le小于等于,-lt小于,-ne不等
字符串比较
str1=str2字符串是否相等,str1=str2字符串是否不同,str1<str2,str1>str2,-n str1 长度是否非0 ,-z str1长度是否为0
if [ $1 = $2 ]
then
 echo "hello"
else
echo "world"
fi

if [ $1 \> $2 ]
then
 echo "hello"
else
echo "world"
fi

if [ -n "$1" ]
then
 echo "hello"
else
echo "world"
fi
文件比较
-d:file是否存在并在同一个目录,-e:检查文件是否存在,-f:检查文件是否存在并且是一个文件、
-r::检查文件是否存在并且可读,,-s:检查文件是否存在并且非空,w检查file是否存在并且可写
-x可执行 -O是否为当前用户所属;-G检查文件是否存在并且默认与当前用户相同
file1  -nt file2 检查是否更新file1  -ot file2 检查是否更旧
if [ -d $HOME ]
then
 echo "hello"
else
echo "world"
fi
if [ ./list -nt ./test ]
then
 echo "hello"
else
echo "world"
fi
复合条件测试
[ condition ] && [ condition ]
[ condition ] || [ condition ]
使用双圆括号:允许使用高级数学表达式放入比较中
((expression))
val++,val--,++val,--val,!逻辑求反,~位求反,**觅求算,<<左位移,>>右位移,&位布尔求和,|位布尔求或,&&逻辑与,||逻辑或
if  (($1++>1))
then
 ((val=$1**100))
 echo $val
else
echo "world"
fi
双方括号:针对字符串比较的高级特性
if  [[ $USER == l* ]]
then
 echo "hello"
else
echo "world"
fi
case命令
case $1 in
hello) echo "hello";;
world) echo "world" ;;
esac
遍历目录
for f in `ls -trl`
do
 echo "the file : $f"
done

对变量读取列表
list="alabama alask acd kxsoa "
for state in $list

从命令读取
for state in `cat $file`
更改字段的分隔符(默认的为空格,字表,换行)
IFS=$'\n'

指定多个分隔符
IFS=$'\N;:"'
IFS.OLD=$IFS
IFS=$'\N;:"'
IFS=$IFS.OLD
//for循环
for(((i=1;i <=10;i++))
do
echo $i
done
while [ $var -gt 0 ]
do
done
//break &continnue
for  i in 1 2 3 4 5 6 7 8 9
do
if [ $i -eq 5 ]
then
 break;
fi
echo $i
done



 



转载于:https://my.oschina.net/goudingcheng/blog/603264

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值