自動提供設定 shell 腳本的執行權限

自動提供設定 shell 腳本的執行權限

我經常使用 shell 腳本。實際上每次,我都會創建腳本並嘗試運行它,但會收到權限錯誤,因為我忘記設定+x.這看起來是一個巨大的麻煩,有沒有辦法讓我的 shell ( zsh) 自動詢問我是否要添加執行權限並重試,而不是僅僅給我錯誤?

我知道我可以source my.sh,但是採購與運行不同./my.sh,我想要後者。

答案1

不要創建腳本,而是考慮創建功能(並將現有腳本轉換為函數)。這樣,您就再也不用擔心權限問題了。

腳本很容易轉換為函數:

  1. .sh從檔案名稱中刪除副檔名。 (技術上是可選的,但是這就是慣例.)
  2. 確保檔案的父目錄位於您的$fpath.
  3. autoload你的函數在你的.zshrc.

如果不同的項目需要不同的功能,可以考慮使用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

相關內容