2017-10-12 56 views
1

我只是想知道有無論如何來源文件,然後再次追蹤源文件?Bash腳本重新源文件

我在我的bash腳本上使用https://github.com/renatosilva/easyoptions,我在主腳本上找到easyoption.sh,並且工作正常。但是當我有其他腳本從主腳本稍後加載時,我想要easyoptions.sh來源,並且--help應該在最後加載的文件上工作。

例如:

test.sh

#!/bin/bash 

## EasyOptions Sub Test 
## Copyright (C) Someone 
## Licensed under XYZ 
##  -h, --help    All client scripts have this, it can be omitted. 

script_dir=$(dirname "$BASH_SOURCE") 
# source "${script_dir}/../easyoptions" || exit # Ruby implementation 
source "${script_dir}/easyoptions.sh" || exit # Bash implementation, slower 

main.sh

#!/bin/bash 

## EasyOptions Main 
## Copyright (C) Someone 
## Licensed under XYZ 
## Options: 
##  -h, --help    All client scripts have this, it can be omitted. 
##   --test  This loads test.sh. 

script_dir=$(dirname "$BASH_SOURCE") 
# source "${script_dir}/../easyoptions" || exit # Ruby implementation 
source "${script_dir}/easyoptions.sh" || exit # Bash implementation, slower 

if [[ -n "$test" ]];then 
    source "${script_dir}/test.sh" 
fi 

現在,當我嘗試 ./main.sh --help 它顯示

EasyOptions Main 
     Copyright (C) Someone 
     Licensed under XYZ 
     Options: 
      -h, --help    All client scripts have this, it can be omitted. 
>    --test  This loads test.sh. 

現在我想下面的工作 ./main.sh --test --help ,它應該輸出

EasyOptions Sub Test 
     Copyright (C) Someone 
     Licensed under XYZ 
      -h, --help    All client scripts have this, it can be omitted. 

但相反,它總是顯示main.sh幫助

回答

1

main.sh當你source easyoptions.sh它將解析所有命令行選項(包括--help--test)。稍後當source test.sheasyoptions將無法​​解析(即它不會看到--help)。您可以在source test.sh之前通過添加echo "[email protected]"來驗證此情況。

+0

真的,我必須解決它。 –

1

爲@pynexj說,「當你源easyoptions.sh它會分析所有的命令行選項」 所以你需要以下步驟:

1.you需要檢查的論點主要過程:

1.1如果第一個參數是--help(第一個參數意味着$ 1,而不是$ 0「文件名」),則顯示主幫助,

1.2如果第一個參數是--test,加載test.sh並傳遞其他參數給孩子的論據。

  • 如果子進程得到的說法--help,這表明孩子的幫助。
  • 這裏是一個簡單的例子,將main.sh的參數傳遞給child(proc.sh)。

    main.sh:

    echo "main:" 
    echo $1 
    echo $2 
    source ./proc.sh $2 
    

    PROC。SH:

    echo "proc:" 
    echo $1 
    
    當您運行CMD

    ./main.sh test help 
    

    輸出

    main: 
    test 
    help 
    proc: 
    help 
    

    你可以看到,main.sh的第二個參數傳遞給孩子

    +0

    我想使用https://github.com/renatosilva/easyoptions,但感謝看到您的解決方案後,我有一個想法,跳過顯示幫助 - 幫助不是第一個選項。哪些工作,但現在問題是我不能重新來源easyoptions第二次,所以我必須找到一個解決方案。 –