shell中判断空字符串和有趣的空字符串

Introduction

Shell 中判断空字符串
以及有趣的空字符串

判断字符串是否为空

Example1

if [[ -z "$str" ]]
then
        echo "1 empty"
fi

Example2

if [[ "$str"x = "x" ]]
then
        echo "2 empty"
fi

Example3

if [[ "$str" = "" ]]
then
        echo "2 empty"
fi

有趣的 空字符串

root@pts/4 $ cat /tmp/lc-7.sh
#!/usr/bin/env bash

str=$1

if [[ "$str" = "" ]]
then
        echo "1 empty"
fi

if [[ "$str" = " " ]]
then
        echo "2 empty"
fi

if [[ "$str" = "0" ]]
then
        echo "3 empty"
fi

if [[ "$str" = "00" ]]
then
        echo "4 empty"
fi

if [[ "$str" -eq 0 ]]
then
        echo "5 empty"
fi

if [[ "$str" -eq 000 ]]
then
        echo "6 empty"
fi

if [[ "$str" -eq '0' ]]
then
        echo "7 empty"
fi

if [[ "$str" -eq '00' ]]
then
        echo "8 empty"
fi

## show results
root@pts/4 $ bash /tmp/lc-7.sh
1 empty
5 empty
6 empty
7 empty
8 empty

从最后的结果中你发现了什么?

欢迎大家留言讨论

《shell中判断空字符串和有趣的空字符串》 公众号: DailyJobOps

    原文作者:全栈运维
    原文地址: https://www.jianshu.com/p/8f59426bfdd0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞