小编All*_*sey的帖子

在Bash中测试非零长度字符串:[ - n"$ var"]或["$ var"]

我已经看到bash脚本以两种不同的方式测试非零长度字符串.大多数脚本使用-n选项:

#!/bin/bash
# With the -n option
if [ -n "$var" ]; then
  # Do something when var is non-zero length
fi
Run Code Online (Sandbox Code Playgroud)

但是-n选项并不是真正需要的:

# Without the -n option
if [ "$var" ]; then
  # Do something when var is non-zero length
fi
Run Code Online (Sandbox Code Playgroud)

哪种方式更好?

同样,这是测试零长度的更好方法:

if [ -z "$var" ]; then
  # Do something when var is zero-length
fi
Run Code Online (Sandbox Code Playgroud)

要么

if [ ! "$var" ]; then
  # Do something when var is zero-length
fi
Run Code Online (Sandbox Code Playgroud)

syntax bash shell if-statement

160
推荐指数
4
解决办法
12万
查看次数

标签 统计

bash ×1

if-statement ×1

shell ×1

syntax ×1