Run a script in the same directory as the current script

前端 未结 2 1297
走了就别回头了
走了就别回头了 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:38

    $0 is considered unsafe by many devs. I have found another solution, it is safe for a chain of bash scripts and source.

    If a.sh needs to execute b.sh (located in the same folder) using a child bash process:

    #!/bin/bash
    __dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    bash ${__dir}/b.sh
    

    If a.sh needs to execute b.sh (located in the same folder) using the same bash process:

    #!/bin/bash
    __dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    source ${__dir}/b.sh
    

提交回复
热议问题