Bash 风格:用条件定义的缩进函数?
Bash style: indent function defined with conditional?
如果要有条件控制定义了哪个版本的函数(而不是在函数中有条件)
函数应该缩进是否有统一的协议?
if whatever; then
function myfunc() {
echo "impl 1"
}
else
function myfunc() {
echo "impl 2"
}
fi
对
if whatever; then
function myfunc() {
echo "impl 1"
}
else
function myfunc() {
echo "impl 2"
}
fi
(仅回答缩进问题,不涉及关键字函数的使用、大括号的位置等)
见仁见智:对,缩进。
作为一个更 objective 的陈述(我更愿意自称是一个普遍的观点):使用与正文中任何其他陈述相同的缩进(或不缩进)有条件的。即写
if whatever; then
function foo {
...
}
fi
if whatever; then
foo=3
fi
或
if whatever; then
function foo {
...
}
fi
if whatever; then
foo=3
fi
这样做的理由是除了语法之外,函数定义只是一个赋值。它不是将字符串分配给参数名称,而是绑定复合命令。事实上,即使在发现 ShellShock 漏洞后所做的更改之后,仍然可以通过环境变量在 bash
中动态定义一个函数(模仿 bash
本身导出函数定义正常的方式方式):
$ env "BASH_FUNC_foo%%=() { echo 1; }" bash
$ foo
1
因此,就缩进而言,没有理由将其与任何其他赋值语句区别对待。
如果要有条件控制定义了哪个版本的函数(而不是在函数中有条件)
函数应该缩进是否有统一的协议?
if whatever; then
function myfunc() {
echo "impl 1"
}
else
function myfunc() {
echo "impl 2"
}
fi
对
if whatever; then
function myfunc() {
echo "impl 1"
}
else
function myfunc() {
echo "impl 2"
}
fi
(仅回答缩进问题,不涉及关键字函数的使用、大括号的位置等)
见仁见智:对,缩进。
作为一个更 objective 的陈述(我更愿意自称是一个普遍的观点):使用与正文中任何其他陈述相同的缩进(或不缩进)有条件的。即写
if whatever; then
function foo {
...
}
fi
if whatever; then
foo=3
fi
或
if whatever; then
function foo {
...
}
fi
if whatever; then
foo=3
fi
这样做的理由是除了语法之外,函数定义只是一个赋值。它不是将字符串分配给参数名称,而是绑定复合命令。事实上,即使在发现 ShellShock 漏洞后所做的更改之后,仍然可以通过环境变量在 bash
中动态定义一个函数(模仿 bash
本身导出函数定义正常的方式方式):
$ env "BASH_FUNC_foo%%=() { echo 1; }" bash
$ foo
1
因此,就缩进而言,没有理由将其与任何其他赋值语句区别对待。