2017-10-12 44 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第二次,所以我必须找到一个解决方案。 –