Run a script in the same directory as the current script

前端 未结 2 1295
走了就别回头了
走了就别回头了 2020-12-14 13:41

I have two Bash scripts in the same folder (saved somewhere by the user who downloads the entire repository):

  • script.sh is run by the user
2条回答
  •  别那么骄傲
    2020-12-14 14:36

    Since $0 holds the full path of the script that is running, you can use dirname against it to get the path of the script:

    #!/bin/bash
    
    script_name=$0
    script_full_path=$(dirname "$0")
    
    echo "script_name: $script_name"
    echo "full path: $script_full_path"
    

    so if you for example store it in /tmp/a.sh then you will see an output like:

    $ /tmp/a.sh
    script_name: /tmp/a.sh
    full path: /tmp
    

    so

    1. Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with /usr/bin/script.sh, with ./script.sh, or it could be with ../Downloads/repo/scr/script.sh)

    Using dirname "$0" will allow you to keep track of the original path.

    1. The script script.sh will be changing to a different directory before calling helper.sh.

    Again, since you have the path in $0 you can cd back to it.

提交回复
热议问题