最近我一直在研究幾個bash腳本,我開始想知道應該如何設置更大的腳本。應該如何根據運行腳本獲取腳本?
bash腳本始終在當前目錄中運行,因此要使用source
,您需要源腳本的絕對路徑。
我看到了this post,但它似乎太複雜了,因爲我預計這是一個常見的用例。
是否有腳本在與運行腳本相同的目錄中獲取腳本的習慣用法?
最近我一直在研究幾個bash腳本,我開始想知道應該如何設置更大的腳本。應該如何根據運行腳本獲取腳本?
bash腳本始終在當前目錄中運行,因此要使用source
,您需要源腳本的絕對路徑。
我看到了this post,但它似乎太複雜了,因爲我預計這是一個常見的用例。
是否有腳本在與運行腳本相同的目錄中獲取腳本的習慣用法?
有沒有36000級的解決方案:
1)絕對路徑:
source /absolute_path/script.sh # sourcing a script
. /absolute_path/script.sh # sourcing a script
/absolute_path/script.sh # executing a script
2)相對路徑:
./script.sh # when script.sh is in the current directory
./dir/script.sh # when script.sh is in the directory 'dir' which is in the current directory
../script.sh # when script.sh is in the parent directory
而且你可以使用source
或. script.sh
使用相對路徑了。
3)使用別名:
echo "alias script='/absolute_path/script.sh'" >> ~/.bashrc
source ~/.bashrc
script # executing script.sh
4)添加到PATH:
echo "export PATH=$PATH:/absolute_path/script.sh" >> ~/.bashrc
source ~/.bashrc
script.sh # executing script.sh
而且知道採購的腳本和執行腳本的區別,看到這個subject。
您可以使用dirname
和$0
揣摩出當前運行的腳本位於(這裏doit2.sh是在同一目錄原始腳本的腳本):
. $(dirname $0)/doit2.sh
很酷。它曾經是$ 0只給你執行的命令,而不是完整的路徑,至少這就是我記憶的方式。任何人都記得嗎? –
這就是我一直在使用的,但是當你運行一個到腳本的符號鏈接時它會中斷。 – everett1992
如果有一個簡單的方法那另一個問題的答案就不會那麼複雜了。 Bash腳本通常不會被分解成許多單獨的腳本,所以它通常不是問題。 – Barmar
另一個問題涉及一般用例,而我只想提供其他腳本。我沒有太高的期望,但我認爲這值得提問。 – everett1992
不要破壞你的腳本。如果太長(超過1000行),請考慮使用其他語言。 –