skip to Main Content

I have the following path in my $PATH: /home/ubuntu/parent-dir/scripts.
I can access every scripts that’s inside of the scripts directory.
However, I would like to access a script inside of /home/ubuntu/parent-dir/scripts/child-dir without editing my $PATH. Is it possible

example:
/home/ubuntu/parent-dir/scripts/child-dir/script.sh

2

Answers


  1. Chosen as BEST ANSWER

    Ended up adding to $PATH="$PATH:/home/ubuntu/parent-dir/scripts/child-dir


  2. While I don’t consider this good practice (i.e. adding the other directory to $PATH is way better), but you certainly could iterate through the individual paths defined in $PATH, and each time check if the script exists relative to there. If so, execute it, otherwise continue looping.

    exec_rel_to_PATH() (
      IFS=:; for p in $PATH; do [ -x "$p/$1" ] && { "$p/$1"; return; }; done;
    )
    
    exec_rel_to_PATH child-dir/script.sh
    

    Note: This is not limited in childward direction. exec_rel_to_PATH ../../uncle-dir/other-scripts/script.sh should work as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search