#!/bin/bash
if [ -z "$2" ]; then
zone="public"
else
zone="$2"
fi
echo "The zone is set to: $zone"
现在,我们用不同的参数来运行这个脚本:
- `bash example.sh arg1`: 这里只传递了一个参数,所以`$2`为空。脚本会将`zone`设置为`"public"`,输出将是:"The zone is set to: public"。
- `bash example.sh arg1 arg2`: 这里传递了两个参数,`$2`不为空,所以`zone`会被设置为`"arg2"`,输出将是:"The zone is set to: arg2"。
- `bash example.sh arg1 ""`: 这里第二个参数是一个空字符串,`-z`测试会认为它为空,所以`zone`会被设置为`"public"`,输出将是:"The zone is set to: public"。
这个脚本的目的是确保`zone`变量有一个值,如果用户没有提供第二个参数,就默认设置为`"public"`。