bash shell store path to current file as variable?

This question already has an answer here:

  • Getting the source directory of a Bash script from within 50 answers
  • Bash get current directory of file after getting called by another bash script [duplicate] 2 answers

  • If I am understanding at all where you want to go with this, my recommendation would be

  • Make the code work out of the current directory as far as possible.
  • Don't litter the user's environment with multiple variables if it can be avoided.
  • If you have to have environment variables, give them a name which clearly communicates what they are related to.
  • In some more concretion, a single variable which names the project root should be all you really need. Don't require it to be set if the expected files are in the current directory.

    export NUC_SEG_DIR=$HOME/nuclei_segmentation
    

    In your Python code, put in reasonable defaults. In this particular case, expect os.path.join(os.environ['NUC_SEG_DIR'], 'data') to point to your data directory, etc. If users want to override this, that's easy enough with symbolic links. Make sure this is parametrized in the code so that it's easy to override in a single place if you should want to make this configurable in the future. Maybe something like

    def nuc_seg(root_dir=os.environ['NUC_SEG_DIR'], data_dir='./data', model_dir='./models', output_dir='./output'):
        if root_dir == '':
            root_dir='.'
        ... your code here
    

    and perhaps later on make your command-line interface let the user override these values by way of command-line options or a configuration file.

    Again, don't require the user to edit their .bash_profile or similar - what if they want to run multiple experiments in different directories, or whatever? They can figure out how to make the environment variable permanent, or you could even document this as an option if your users can't be expected to be familiar with the basics of the shell.


    在脚本文件中使用dirname $0来查找当前脚本文件所在的目录

    链接地址: http://www.djcxy.com/p/9760.html

    上一篇: 如何回显从另一个位置执行的脚本的路径?

    下一篇: bash shell将当前文件的路径存储为变量?