最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

讓代碼整潔、過程清晰的BASH Shell編程技巧

 更新時(shí)間:2014年07月23日 10:24:36   投稿:junjie  
這篇文章主要介紹了讓代碼整潔、過程清晰的BASH Shell編程技巧,特別是大型的Shell項(xiàng)目中,這10個(gè)經(jīng)驗(yàn)之談可以幫助你寫出代碼整潔、過程清晰的代碼,需要的朋友可以參考下

這是我寫B(tài)ASH程序的招式。這里本沒有什么新的內(nèi)容,但是從我的經(jīng)驗(yàn)來看,人們愛濫用BASH。他們忽略了計(jì)算機(jī)科學(xué),而從他們的程序中創(chuàng)造的是“大泥球”(譯注:指架構(gòu)不清晰的軟件系統(tǒng))。

在此我告訴你方法,以保護(hù)你的程序免于障礙,并保持代碼的整潔。

一、不可改變的全局變量

1.盡量少用全局變量
2.以大寫命名
3.只讀聲明
4.用全局變量來代替隱晦的$0,$1等

在我的程序中常使用的全局變量:

復(fù)制代碼 代碼如下:

readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
readonly ARGS="$@"

二、一切皆是局部的

所有變量都應(yīng)為局部的。

復(fù)制代碼 代碼如下:

change_owner_of_file() {
    local filename=$1
    local user=$2
    local group=$3

    chown $user:$group $filename
}
change_owner_of_files() {
    local user=$1; shift
    local group=$1; shift
    local files=$@
    local i

    for i in $files
    do
        chown $user:$group $i
    done
}

1.自注釋(self documenting)的參數(shù)
2.通常作為循環(huán)用的變量i,把它聲明為局部變量是很重要的。
3.局部變量不作用于全局域。

復(fù)制代碼 代碼如下:

kfir@goofy ~ $ local a
bash: local: can only be used in a function

三、main()

1.有助于保持所有變量的局部性
2.直觀的函數(shù)式編程
3.代碼中唯一的全局命令是:main

復(fù)制代碼 代碼如下:

main() {
    local files="/tmp/a /tmp/b"
    local i

    for i in $files
    do
        change_owner_of_file kfir users $i
    done
}
main

四、一切皆是函數(shù)

唯一全局性運(yùn)行的代碼是:
- 不可變的全局變量聲明
- main()函數(shù)

1.保持代碼整潔
2.過程變得清晰

復(fù)制代碼 代碼如下:

main() {
    local files=$(ls /tmp | grep pid | grep -v daemon)
}

復(fù)制代碼 代碼如下:

temporary_files() {
    local dir=$1

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

main() {
    local files=$(temporary_files /tmp)
}

1.第二個(gè)例子好得多。查找文件是temporary_files()的問題而非main()的。這段代碼用temporary_files()的單元測(cè)試也是可測(cè)試的。

2.如果你一定要嘗試第一個(gè)例子,你會(huì)得到查找臨時(shí)文件以和main算法的大雜燴。

復(fù)制代碼 代碼如下:

test_temporary_files() {
    local dir=/tmp

    touch $dir/a-pid1232.tmp
    touch $dir/a-pid1232-daemon.tmp

    returns "$dir/a-pid1232.tmp" temporary_files $dir

    touch $dir/b-pid1534.tmp

    returns "$dir/a-pid1232.tmp $dir/b-pid1534.tmp" temporary_files $dir
}

如你所見,這個(gè)測(cè)試不關(guān)心main()。

五、調(diào)試函數(shù)

帶-x標(biāo)志運(yùn)行程序:

復(fù)制代碼 代碼如下:

bash -x my_prog.sh

只調(diào)試一小段代碼,使用set-x和set+x,會(huì)只對(duì)被set -x和set +x包含的當(dāng)前代碼打印調(diào)試信息。

復(fù)制代碼 代碼如下:

temporary_files() {
    local dir=$1

    set -x
    ls $dir \
        | grep pid \
        | grep -v daemon
    set +x
}

打印函數(shù)名和它的參數(shù):

復(fù)制代碼 代碼如下:

temporary_files() {
    echo $FUNCNAME $@
    local dir=$1

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

調(diào)用函數(shù):

復(fù)制代碼 代碼如下:

temporary_files /tmp

會(huì)打印到標(biāo)準(zhǔn)輸出:

復(fù)制代碼 代碼如下:
temporary_files /tmp

六、代碼的清晰度

這段代碼做了什么?

復(fù)制代碼 代碼如下:

main() {
    local dir=/tmp

    [[ -z $dir ]] \
        && do_something...

    [[ -n $dir ]] \
        && do_something...

    [[ -f $dir ]] \
        && do_something...

    [[ -d $dir ]] \
        && do_something...
}
main

讓你的代碼說話:

復(fù)制代碼 代碼如下:

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

七、每一行只做一件事

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

復(fù)制代碼 代碼如下:

temporary_files() {
    local dir=$1

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

可以寫得簡(jiǎn)潔得多:

復(fù)制代碼 代碼如下:

temporary_files() {
    local dir=$1

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

符號(hào)在縮進(jìn)行的開始

符號(hào)在行末的壞例子:(譯注:原文在此例中用了temporary_files()代碼段,疑似是貼錯(cuò)了。結(jié)合上下文,應(yīng)為print_dir_if_not_empty())

復(fù)制代碼 代碼如下:

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

好的例子:我們可以清晰看到行和連接符號(hào)之間的聯(lián)系。

復(fù)制代碼 代碼如下:

print_dir_if_not_empty() {
    local dir=$1

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

八、打印用法

不要這樣做:

復(fù)制代碼 代碼如下:

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

它應(yīng)該是個(gè)函數(shù):

復(fù)制代碼 代碼如下:

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

echo在每一行重復(fù)。因此我們得到了這個(gè)文檔:

復(fù)制代碼 代碼如下:

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
}

注意在每一行的行首應(yīng)該有一個(gè)真正的制表符‘\t'。

在vim里,如果你的tab是4個(gè)空格,你可以用這個(gè)替換命令:

復(fù)制代碼 代碼如下:

:s/^    /\t/

九、命令行參數(shù)

這里是一個(gè)例子,完成了上面usage函數(shù)的用法。我從http://kirk.webfinish.com/2009/10/bash-shell-script-to-use-getopts-with-gnu-style-long-positional-parameters/ 得到這段代碼

復(fù)制代碼 代碼如下:

cmdline() {
    # got this idea from here:
    # http://kirk.webfinish.com/2009/10/bash-shell-script-to-use-getopts-with-gnu-style-long-positional-parameters/
    local arg=
    for arg
    do
        local delim=""
        case "$arg" in
            #translate --gnu-long-options to -g (short options)
            --config)         args="${args}-c ";;
            --pretend)        args="${args}-n ";;
            --test)           args="${args}-t ";;
            --help-config)    usage_config && exit 0;;
            --help)           args="${args}-h ";;
            --verbose)        args="${args}-v ";;
            --debug)          args="${args}-x ";;
            #pass through anything else
            *) [[ "${arg:0:1}" == "-" ]] || delim="\""
                args="${args}${delim}${arg}${delim} ";;
        esac
    done

    #Reset the positional parameters to the short options
    eval set -- $args

    while getopts "nvhxt:c:" OPTION
    do
         case $OPTION in
         v)
             readonly VERBOSE=1
             ;;
         h)
             usage
             exit 0
             ;;
         x)
             readonly DEBUG='-x'
             set -x
             ;;
         t)
             RUN_TESTS=$OPTARG
             verbose VINFO "Running tests"
             ;;
         c)
             readonly CONFIG_FILE=$OPTARG
             ;;
         n)
             readonly PRETEND=1
             ;;
        esac
    done

    if [[ $recursive_testing || -z $RUN_TESTS ]]; then
        [[ ! -f $CONFIG_FILE ]] \
            && eexit "You must provide --config file"
    fi
    return 0
}

你像這樣,使用我們?cè)陬^上定義的不可變的ARGS變量:

復(fù)制代碼 代碼如下:

main() {
    cmdline $ARGS
}
main

十、單元測(cè)試

1.在更高級(jí)的語言中很重要。
2.使用shunit2做單元測(cè)試

復(fù)制代碼 代碼如下:

test_config_line_paths() {
    local s='partition cpm-all, 80-90,'

    returns "/a" "config_line_paths '$s /a, '"
    returns "/a /b/c" "config_line_paths '$s /a:/b/c, '"
    returns "/a /b /c" "config_line_paths '$s   /a  :    /b : /c, '"
}

config_line_paths() {
    local partition_line="$@"

    echo $partition_line \
        | csv_column 3 \
        | delete_spaces \
        | column 1 \
        | colons_to_spaces
}

source /usr/bin/shunit2

這里是另一個(gè)使用df命令的例子:

復(fù)制代碼 代碼如下:

DF=df

mock_df_with_eols() {
    cat <<- EOF
    Filesystem           1K-blocks      Used Available Use% Mounted on
    /very/long/device/path
                         124628916  23063572 100299192  19% /
    EOF
}

test_disk_size() {
    returns 1000 "disk_size /dev/sda1"

    DF=mock_df_with_eols
    returns 124628916 "disk_size /very/long/device/path"
}

df_column() {
    local disk_device=$1
    local column=$2

    $DF $disk_device \
        | grep -v 'Use%' \
        | tr '\n' ' ' \
        | awk "{print \$$column}"
}

disk_size() {
    local disk_device=$1

    df_column $disk_device 2
}

這里我有個(gè)例外,為了測(cè)試,我在全局域中聲明了DF為非只讀。這是因?yàn)閟hunit2不允許改變?nèi)钟蚝瘮?shù)。

相關(guān)文章

  • 詳細(xì)介紹Linux IO

    詳細(xì)介紹Linux IO

    這篇文章主要介紹了Linux IO,對(duì)Linux感興趣的同學(xué),可以參考下
    2021-04-04
  • Shell中函數(shù)返回值超出問題

    Shell中函數(shù)返回值超出問題

    這篇文章主要介紹了Shell中函數(shù)返回值超出問題,shell中通過return返回是有限制的,最大返回255,超過255,則從0開始計(jì)算,需要的朋友可以參考下
    2015-05-05
  • Window11?WSL2?添加靜態(tài)IP的腳本

    Window11?WSL2?添加靜態(tài)IP的腳本

    這篇文章主要介紹了Window11?WSL2?添加靜態(tài)IP的腳本方法,通過一段腳本給?Windows?端的"vEthernet?(WSL)"加了IPv4?172.18.16.1,給?Linux?端的?eth0?添加?IPv4?172.18.16.1,在使用前,請(qǐng)按需調(diào)整網(wǎng)絡(luò)接口的名稱和IP地址,需要的朋友可以參考下
    2023-01-01
  • linux定時(shí)器crontab的使用教程

    linux定時(shí)器crontab的使用教程

    這篇文章主要介紹了linux定時(shí)器crontab的使用教程,需要的朋友可以參考下
    2018-08-08
  • shell向文件中添加新內(nèi)容的實(shí)現(xiàn)方法

    shell向文件中添加新內(nèi)容的實(shí)現(xiàn)方法

    Shell腳本是一種為shell編寫的腳本程序,下面這篇文章主要給大家介紹了關(guān)于shell向文件中添加新內(nèi)容的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2023-06-06
  • linux?命令中的lynx解析

    linux?命令中的lynx解析

    lynx命令是純文本模式的網(wǎng)頁瀏覽器,不支持圖形、音頻、視頻等多媒體信息,這篇文章主要介紹了linux?命令中的lynx解析,需要的朋友可以參考下
    2024-07-07
  • Linux下去掉^M的四種方法

    Linux下去掉^M的四種方法

    本文通過四種方法給大家介紹了Linux下去掉^M的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-06-06
  • bash腳本輸入密碼不回顯問題的解決方法

    bash腳本輸入密碼不回顯問題的解決方法

    編寫一個(gè)bash腳本時(shí),需要用戶輸入一個(gè)密碼,方可繼續(xù)后續(xù)流程,但是又要保證用戶輸入的密碼不會(huì)被別人看到,因此排除了通過參數(shù)將密碼傳入腳本的方案
    2013-08-08
  • Linux 中wget命令詳細(xì)介紹

    Linux 中wget命令詳細(xì)介紹

    這篇文章主要介紹了Linux 中wget命令詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • Shell編程中Shift的用法小結(jié)

    Shell編程中Shift的用法小結(jié)

    本文給大家分享Shell編程中Shift的用法小結(jié),文末文給大家擴(kuò)展介紹Shell grep 命令擴(kuò)展增強(qiáng)問題分析,感興趣的朋友跟隨小編一起看看吧
    2021-07-07

最新評(píng)論

牙克石市| 商都县| 行唐县| 博兴县| 德州市| 池州市| 平遥县| 安化县| 喀喇沁旗| 德格县| 抚松县| 衡东县| 上饶县| 遂昌县| 白水县| 伊春市| 大英县| 长顺县| 宣汉县| 天津市| 阳信县| 临邑县| 广丰县| 临朐县| 望奎县| 齐河县| 本溪| 清镇市| 巴彦淖尔市| 普宁市| 海南省| 巴青县| 屯昌县| 手机| 盐津县| 仲巴县| 确山县| 舒兰市| 阳西县| 凌源市| 苗栗县|