代码的清晰度这段代码做了什么? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | main() {
local dir = /tmp
[[ -z $ dir ]] \
&& do_something...
[[ -n $ dir ]] \
&& do_something...
[[ -f $ dir ]] \
&& do_something...
[[ -d $ dir ]] \
&& do_something...
}
main
|
让你的代码说话: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | is_empty() {
local var=$1
[[ -z $var ]]
}
is_not_empty() {
local var=$1
[[ -n $var ]]
}
is_file() {
local file =$1
[[ -f $ file ]]
}
is_dir() {
local dir =$1
[[ -d $ dir ]]
}
main() {
local dir = /tmp
is_empty $ dir \
&& do_something...
is_not_empty $ dir \
&& do_something...
is_file $ dir \
&& do_something...
is_dir $ dir \
&& do_something...
}
main
|
每一行只做一件事1 2 3 4 5 | temporary_files() {
local dir =$1
ls $ dir | grep pid | grep - v daemon
}
|
可以写得简洁得多: 1 2 3 4 5 6 7 | temporary_files() {
local dir =$1
ls $ dir \
| grep pid \
| grep - v daemon
}
|
符号在行末的坏例子:(译注:原文在此例中用了temporary_files()代码段,疑似是贴错了。结合上下文,应为print_dir_if_not_empty()) 1 2 3 4 5 6 7 | print_dir_if_not_empty() {
local dir =$1
is_empty $ dir && \
echo "dir is empty" || \
echo "dir=$dir"
}
|
好的例子:我们可以清晰看到行和连接符号之间的联系。 1 2 3 4 5 6 7 | print_dir_if_not_empty() {
local dir =$1
is_empty $ dir \
&& echo "dir is empty" \
|| echo "dir=$dir"
}
|
打印用法不要这样做: 1 2 3 | echo "this prog does:..."
echo "flags:"
echo "-h print help"
|
它应该是个函数: 1 2 3 4 5 | usage() {
echo "this prog does:..."
echo "flags:"
echo "-h print help"
}
|
echo在每一行重复。因此我们得到了这个文档: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | usage() {
cat <<- EOF
usage: $PROGNAME options
Program deletes files from filesystems to release space.
It gets config file that define fileystem paths to work on, and whitelist rules to
keep certain files.
OPTIONS:
-c --config configuration file containing the rules. use --help-config to see the syntax.
-n --pretend do not really delete, just how what you are going to do .
-t -- test run unit test to check the program
- v --verbose Verbose. You can specify more then one - v to have more verbose
-x --debug debug
-h --help show this help
--help-config configuration help
Examples:
Run all tests:
$PROGNAME -- test all
Run specific test :
$PROGNAME -- test test_string.sh
Run:
$PROGNAME --config /path/to/config/ $PROGNAME.conf
Just show what you are going to do :
$PROGNAME -vn -c /path/to/config/ $PROGNAME.conf
EOF
}
|
注意在每一行的行首应该有一个真正的制表符‘\t’。 在vim里,如果你的tab是4个空格,你可以用这个替换命令:
|