在Bash中测试非零长度字符串:[ - n“$ var”]或[“$ var”]
我已经看到bash脚本以两种不同的方式测试非零长度字符串。大多数脚本使用-n选项:
#!/bin/bash# With the -n optionif [ -n "$var" ]; then # Do something when var is non-zero lengthfi
但是-n选项并不是真正需要的:
# Without the -n optionif [ "$var" ]; then # Do something when var is non-zero lengthfi
哪种方式更好?
同样,这是测试零长度的更好方法:
if [ -z "$var" ]; then # Do something when var is zero-lengthfi
要么
if [ ! "$var" ]; then # Do something when var is zero-lengthfi
手掌心