让代码整洁、过程清晰的BASH Shell编程技巧

2019-09-23 09:36:52于海丽

        && do_something...
}
main

七、每一行只做一件事

用反斜杠来作分隔符。例如:

temporary_files() {
    local dir=$1

    ls $dir | grep pid | grep -v daemon
}

可以写得简洁得多:

temporary_files() {
    local dir=$1

    ls $dir
        | grep pid
        | grep -v daemon
}

符号在缩进行的开始

符号在行末的坏例子:(译注:原文在此例中用了temporary_files()代码段,疑似是贴错了。结合上下文,应为print_dir_if_not_empty())


print_dir_if_not_empty() {
    local dir=$1
 
    is_empty $dir &&
        echo "dir is empty" ||
        echo "dir=$dir"
}

好的例子:我们可以清晰看到行和连接符号之间的联系。

print_dir_if_not_empty() {
    local dir=$1

    is_empty $dir
        && echo "dir is empty"
        || echo "dir=$dir"
}

八、打印用法

不要这样做:

echo "this prog does:..."
echo "flags:"
echo "-h print help"

它应该是个函数:

usage() {
    echo "this prog does:..."
    echo "flags:"
    echo "-h print help"
}

echo在每一行重复。因此我们得到了这个文档:

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