我想寫一個從shebang行調用的腳本,並根據條件返回正確的解釋器(在我的情況下,基於操作系統版本),我不明白爲什麼它不起作用。
我會嘗試通過一個例子來闡明:
可執行文件1:/home/orens/dynamically_select_interpreter/select_interpreter.sh:如何在shebang行中動態選擇解釋器?
#!/usr/bin/env bash
echoerr() { echo "[email protected]" 1>&2; }
interpreter=`cat /home/orens/dynamically_select_interpreter/interpreter`
if [ -z "$interpreter" ]; then
echoerr "Could not find interpreter!"
exit 1
fi
echoerr "Found interpreter: $interpreter"
exec "$interpreter" "[email protected]"
此腳本選擇基於一些文件的內容翻譯(中這種情況下的內容是:/usr/bin/python
)。然後,它通過調用exec
替換正確的解釋器。
從命令行調用它,這就是我得到:
$ /home/orens/dynamically_select_interpreter/select_interpreter.sh
Found interpreter: /usr/bin/python
Python 2.4.3 (#1, Dec 10 2010, 17:24:35)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
然而,當我嘗試使用它家當線內,像這樣:
#!/home/orens/dynamically_select_interpreter/select_interpreter.sh
echo $SHELL # should be an error # LINE 1
import sys; print "HERE"; print sys.version # this is the actual error # LINE 2
腳本的執行shell腳本而不是python腳本。 LINE 1正確執行,LINE 2發生錯誤。看起來shebang行被默默忽略(甚至打印到stderr也不顯示在屏幕上)。
基本上,我試圖做的env
相同,但從腳本。我猜如果我用C/C++編寫它並編譯,我會得到我想要的,但是由於這個腳本將被用作克服多內核版本情況的工具,我真的很希望我的可執行文件成爲OS-獨立和我的唯一方法來實現這一點是由腳本。
任何人都可以解釋這種行爲或幫助我解決它嗎?
謝謝!
的腳本只是在$ @第一個成員。然而,我的確給了你的建議一個嘗試,它不起作用,因爲$ 0是腳本本身的名字(在這個例子中是select_interpreter.sh)。 –