shell 基础(一)
2015-08-09 21:59
435 查看
shell 基础
1. shell 数学运算
1.1 let命令 :
num1=1;num2=2;
let result=num1+num2;
let result++;
echo $result;
4
1.2 操作符[] 和 (())
result=[num1+num2];或者result=[ num1 + num2];或者 result=[ $num1 + 5 ];
另外 $(cmda;cmdb;..cmdx) 可以用于执行命令
三种括号的用法
1.3 expr
result=`expr 5 + 8`;result=$(expr $num1 + 5);
1.4 bc
result=$(echo 3*1.5 | bc); 或者 result=`echo 3*1.5 | bc`echo $result
4.5
设置精度
echo “scale=2;7/19” | bc
0.36
进制转换
num=5
echo “obase=2;$num” | bc
101
平方 和平方根
echo “sqrt(81)” | bc
9
echo “10^2” | bc;
100
2.函数
#!/bin/bash 2 3 add() #定义 4 { 5 return `expr $1 + $2`; 6 } 7 add 5 9; #调用 8 result=$?; #取返回值 9 echo "result:$result";
输出:14
3.if语句
if条件if condition;then commands; fi
else 和else if
if condition;then commands; else if condition;then commands; else commands; fi
条件测试
算术比较[ \$var -eq 0 ] [ \$var -ne 0 ] [ \$var -gt 0 ] 大于 [ \$var -lt 0 ] [ \$var -ge 0 ] 大于等于 [ \$var -le 0 ]
文件相关测试
[ -f \$var ] 变量是一个文件路径 [ -x \$var ] 变量是一个文件路径且可执行 [ -d \$var ] 变量是一个目录 [ -r \$var ] 变量是一个可读文件 [ -w \$var ] 变量是一个可写文件 [ -L \$var ] 变量是一个符号链接文件
字符串比较
字符串比较一般用双括号
[[ $str1 = $str2 ]] 或者 [[ $str1 == $str2 ]]
[[ $str1 < $str2 ]] 字母序小于
[[ $str1 > $str2 ]]
[[ -z $str ]] str为空
[[ -n $str ]] str非空
12 str1="abc"; 13 str2=""; 14 if [[ -n $str1 ]] && [[ -z $str2 ]];then 15 echo "str1 not empty, str2 is empty"; 16 else 17 echo "in else "; 18 fi
输出:str1 not empty, str2 is empty
test命令可以代替中括号,执行条件测试
if test $var -eq 0 ;then echo "true"; fi
4.for、while 和 until
-for循环for var in list; do commands; done for i in {1..10}; do commands; done
while循环
while condition do commands; done
untile循环
until condition do commands; done
相关文章推荐
- #每日Linux小练习#06 Shell Script知识点总结(上)
- Linux系统命令及Shell脚本学习笔记二:用户管理
- linux shell学习
- shell注释
- shell运算符
- webshell防范的一点笔记
- shell脚本条件判断
- 【leetcode~Shell】:Tenth Line
- Shell Script - 追踪与debug
- Shell Script - 追踪与debug
- Shell Scripts - 循环while,until,for
- Shell Scripts - 循环while,until,for
- Shell替换
- shell中的read
- Shell特殊变量
- shell的定义
- shell变量
- 【shell脚本练习】grep sed awk
- 【shell脚本练习】grep sed awk
- 第一个shell脚本