Shell脚本学习日志 — 字符串运算符、printf、字符串比较

目录

一、字符串运算符

二、echo和printf

三、运算


一、字符串运算符

#!/bin/bash
echo "字符串运算符"
a="123"
b="abc"
if [ $a = $b ]
then echo "a==b"
else
     echo "a!=b"
fi
#检测字符串长度是否为0
a=""
if [ -z $a ]
then
 echo "a长度为0"
fi
a=""
if [ -z $a ]
then
 echo "a长度为0"
fi
a=""
#检测字符串长度是否不为0
if [ -n "$a" ]
then
 echo "a长度不为0"
else
 echo "a长度为0"
fi
#检测字符串长度是否不为空
if [ $a ]
then
        echo "a不空"
else
        echo "a为空"
fi

二、echo和printf

#!/bin/bash

echo "echo命令"
echo string
echo "string"
echo "\"string\""
# -e 开启转义字符 \c 不换行
echo -e "123\c"
echo "456"

#Shell printf 命令
printf "hello\n"
printf 123
printf "\n"

printf %s 123
printf "\n"

printf "%d-%d-%d\n" 4 5 6

a=12.544
str="Shell"
printf "a=%.2f,str=%s\n" $a $str

三、运算

#!/bin/bash
echo "test 命令"
a=10
b=2

if test $[a] -eq $[b]
then
    echo a=b
else
    echo a!=b
fi

echo "[]执行基本的算数运算"
echo "几种算数运算"

result=$[a+b]
echo "$a+$b=$result"
#输出为10+2
result=$a+$b
echo "$a+$b=$result"

result=`expr $a + $b`
echo $a+$b=$result

echo "-----------字符串------------"
echo ' =等与则为真
!= 不相等为真
-z 字符串长度为零为真
-n 字符串长度不为零为真'

str1="123"
str2="123"

if test $str1 = $str2
then
    echo $str1=$str2
else
    echo $str1!=$str2
fi

猜你喜欢

转载自blog.csdn.net/qq_53734051/article/details/126568190