我有一個按照慣例/usr/bin/vendor/
添加到的資料夾PATH
,其中包含 shell 腳本等do_something.sh
。現在我想添加一個子資料夾/usr/bin/vendor/some_tool/
來額外儲存一個或多個分組在一起的Perl 腳本,因為它們具有相同的目的,並且我需要額外管理Eclipse 專案文件,甚至可能是設定檔等。得到/usr/bin/vendor/some_tool/do_a.pl
和/usr/bin/vendor/some_tool/do_b.pl
。
因為PATH
,我可以輕鬆地到處調用do_something.sh
。但是有什麼方法可以呼叫some_tool/do_a.pl
相同的方式嗎?確實some_tool/do_a.pl
使用相對路徑,這樣我就知道我正在執行do_a
的任務some_tool
。這幾乎是我想使用相對目錄結構來實現的措詞/命名約定。
在外殼上嘗試過,當然它不起作用,但也許我做錯了什麼,它通常應該可以工作。但我想它不應該,唯一的解決方法是創建一個/usr/bin/vendor/some_tool_do_a.sh
將所有參數轉發到/usr/bin/vendor/some_tool/do_a.pl
.
答案1
手冊bash
頁指定
PATH The search path for commands. It is a colon-separated list of
directories in which the shell looks for commands (see COMMAND
EXECUTION below).
然後它繼續說
If the name is neither a shell function nor a builtin, and contains no
slashes, bash searches each element of the PATH for a directory con‐
taining an executable file by that name.
所以答案似乎是「不,你想做的事情不受支持bash
」。
答案2
不,這是不可能的:/
您鍵入的命令中的任何內容都會使其成為絕對路徑(如果/
是第一個字元),或相對於當前目錄的相對路徑,而不是PATH
條目內的相對路徑。
解決方法可能是將所有腳本連結/usr/bin/vendor/some_tool/
到/usr/bin/vendor/
:
ln [-s] /usr/bin/vendor/some_tool/* /usr/bin/vendor/
可以使用硬連結或軟連結。
如果在呼叫腳本時始終位於同一工作目錄(或少量目錄)中,那麼更簡單的答案可能是從此(或每個)目錄建立相對連結:
ln -s /usr/bin/vendor/some_tool .
在這種情況下,您需要使用符號連結。
其他解決方法可能是定義一個具有短名稱的腳本來執行此功能,您可以使用以下內容來呼叫該腳本:
tl some_tool/do_a.pl
tl
將解析傳遞的參數,逐步PATH
在每個元件中尋找腳本,然後呼叫腳本的完整路徑。
答案3
我在“主”腳本中做了什麼:
mydir=$(dirname "$0")
"$mydir/subdir/otherscript"
那麼主腳本總是能找到孩子,只要他們一起移動,這樣他們的相對位置就不會改變。