![自動提供設定 shell 腳本的執行權限](https://rvso.com/image/178478/%E8%87%AA%E5%8B%95%E6%8F%90%E4%BE%9B%E8%A8%AD%E5%AE%9A%20shell%20%E8%85%B3%E6%9C%AC%E7%9A%84%E5%9F%B7%E8%A1%8C%E6%AC%8A%E9%99%90.png)
我經常使用 shell 腳本。實際上每次,我都會創建腳本並嘗試運行它,但會收到權限錯誤,因為我忘記設定+x
.這看起來是一個巨大的麻煩,有沒有辦法讓我的 shell ( zsh
) 自動詢問我是否要添加執行權限並重試,而不是僅僅給我錯誤?
我知道我可以source my.sh
,但是採購與運行不同./my.sh
,我想要後者。
答案1
不要創建腳本,而是考慮創建功能(並將現有腳本轉換為函數)。這樣,您就再也不用擔心權限問題了。
腳本很容易轉換為函數:
如果不同的項目需要不同的功能,可以考慮使用https://github.com/direnv/direnv。這樣,每個項目都可以有自己的$fpath
功能autoload
。
答案2
這可能有幫助:
function command_permission() {
# Get the command being run
local cmd="${1}"
local cmd=$(echo "${cmd}" | awk '{print $1}' )
# Check if it starts with "./" and if the file doesn't have execute permission
if [[ "${cmd}" =~ ^\./ && ! -x "${cmd#./}" ]]; then
# Prompt for permission to chmod +x the file
read -rq "REPLY?${cmd#./} is not executable. Do you want to make it executable (y/n)? "
"$cmd" "$@"
if [[ "${REPLY}" =~ ^[Yy]$ ]]; then
# Make the file executable
chmod +x "${cmd#./}"
fi
# Add a newline after the prompt
echo ""
fi
}
# Set the preexec function to be called before running each command
autoload -Uz add-zsh-hook
add-zsh-hook preexec command_permission