我见过Bash脚本用两种不同的方式测试长度为非零的字符串。大多数脚本使用-n
选项:
#!/bin/bash
# With the -n option
if [ -n "$var" ]; then
# Do something when var is non-zero length
fi
但是-n选项其实并不需要:
# Without the -n option
if [ "$var" ]; then
# Do something when var is non-zero length
fi
哪一种方法更好?
类似地,哪种是测试零长度的更好方法:
if [ -z "$var" ]; then
# Do something when var is zero-length
fi
或
if [ ! "$var" ]; then
# Do something when var is zero-length
fi