11.7执行数学运算
在shell中执行复杂运算
#!/bin/bash
var1=10.22
var2=11.33
var3=33333
var4=$(bc <<EOF
scale = 4
a1 = ( $var1 * $var2 )
b1 = ($var2 *$var3 )
a1+b1
EOF
)
echo $var4
test [ -rwx e d OG ]
cat new.sh
#!/bin/bash
val=0
valf=5.55
echo "$val"
vals1="str1"
vals2="str2"
if [ $vals1 \< $vals2 ] #< > 符号均需要转义 不然会被解释为重定向
then
echo "vals1 gth vals2"
else
echo " vals1 less than vals2"
fi
if [ $valf -eq 5 ] #不可在test中使用浮点数
then
echo "seixssdasdasdasdas"
fi
Tips:
test 命令使用 数学符号比较字符串;使用文本代码比较数值
#!/bin/bash
str=""
if [ -z $str ] #判断str长度是否为0 -n????
then
echo "str is empty"
else
echo "str is not empty"
fi
测试文件是否为空并写入数据
#!/bin/bash
#
file="opi.txt"
touch $file
if [ -s $file ] #比较成功说明有数据
then
echo "$file is exit!"
else
echo "$file is empty"
ls -al . &>>$file
echo "write successfull"
fi
#!/bin/bash
#check file owership
file=$1
if [ -O $file ]
# -G 比较是否是默认组
then
echo "you are $file's owner!"
else
echo "you are not $file's owner!"
fi
#!/bin/bash
#check file date
#-nt new than 是否比另一个文件新
file1=$1
file2=$2
#-ot older than
if [$file1 -nt $file2 ]
then
echo "$file1 is newer than $file2 "
else
echo "$file1 is older than $file2 "
fi
#!/bin/bash
#testing compound comparisons
#[ ] 内必须有 空格 否则会将 [-w 视为一个命令
file1=$1
if [ -e $file1 ] && [ -w $file1 ]
then
echo "$file1 is exited and writable !"
elif [ -e $file1 ]
then
echo "$file1 is not writable !"
else
echo "$file1 is not exit !"
fi
双括号 (())
双括号支持的运算符号
#!/bin/bash
declare i site=$1
if (( site ** 2 >=100 ))
then
echo "$site*$site>=100"
else
echo "$site*$site<=100"
fi
双方括号
双方括号使用了tset命令的标准字符串比较,同时提供了匹配模式
#!/bin/bash
#using pattern matching
# == 两端同样需要括号
if [[ $USER == u* ]]
then
echo "$USER == u* "
else
echo "$USER != u* "
fi
#!/bin/bash
#test case commmand
#注意 ) 前空格 每次匹配后执行的 ;;
str=$1
case $str in
user )
echo "This is user!" ;;
root )
echo "This is root!" ;;
* )
echo "funny input!" ;;
esac