我已经看到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)