簡體   English   中英

運行包含變量的別名時找不到命令

[英]Command not found when running alias containing variable

我想要 shell 別名有效地識別文件夾,以便在包含.php文件的文件夾中運行命令時,其內容僅為8.1 ,例如,運行相應的二進制文件。

alias php8.0='/opt/homebrew/Cellar/php@8.0/8.0.26/bin/php'
alias php8.1='/opt/homebrew/Cellar/php/8.1.13/bin/php'

alias phpv='php"$(cat .php)" -v'

然而,上面的代碼在運行phpv時返回了一個錯誤command not found php8.1 而單獨運行php8.1 -v可以正常工作。

通常, alias用於縮短您經常鍵入的內容的簡單文本。

alias ll=`ls -l`

如果您正在做比這更復雜的事情,請使用function ,而不是別名。

作為一個練習,讓它接近你的原始想法 - 在你的 PATH 中設置你喜歡的默認值,但是當你想要一個結構來覆蓋它時,而不是一個帶有被破解/解析的數字的本地隱藏文件蒼蠅,創建一個本地符號鏈接到該文件夾中所需的符號鏈接。 雖然這是一個安全問題,但您只需在路徑中設置本地目錄即可。 function 可以通過將更改本地化到特定 function 調用的 scope 來減輕安全問題。

php() { [[ -L ./php ]] && local PATH=".:$PATH";         # only localize if local symlink exists
  local php=$(which php --skip-alias --skip-functions); # variable gets PATH-relevant version
  if [[ -x "$php" ]]                                    # checks for relevant success
  then "$php" "$@"                                      # runs appropriate version
  else "No PHP available."                              # reports if none
  fi
}

當您開始需要需要一個版本或另一個版本的整個子目錄結構時,這會下降,因為現在您必須將該符號鏈接(或 .php 文件或其他文件)放入該結構中的每個文件夾中,這是一團糟和維護噩夢.

更好的解決方案是設置盡可能干凈的結構,並嘗試將(僅)最高/最短的目錄路徑放在所有項目的頂部,並將需要備用版本的其他勘誤表放入查找中。

phpv() { 
  local php='php'
  local -A altv=(
    [/first/dir/to/edit]="/opt/homebrew/Cellar/php@8.0/8.0.26/bin/php"
    [/next/dir]="/some/other/version/bin/php"
    [/next/dir/for/edits]="/opt/homebrew/Cellar/php@8.0/8.0.26/bin/php"
  )
  d="$PWD"                       # set longest path to check
  while [[ -n "$d" ]]
  do if [[ -n "${altv[$PWD]}" ]] # if there's an override
     then php="${altv[$PWD]}"    # override the varible
          break                  # get out, using the longest match
     fi
     d=${d%/*}                   # check one directory higher for an override
  done
  $php" "$@"                     # runs appropriate version
}

這樣,如果您運行phpv -v (或使用任何其他參數集),它應該使用最長匹配檢查您在哪里獲得覆蓋的位置列表,這允許在子目錄中進行不同的覆蓋,但只需要覆蓋到列出需要使用備用版本的最高、最短路徑。 如果沒有為您的當前目錄或任何父目錄找到覆蓋,那么您默認為您的 PATH 中設置的任何內容。

使用我包含的示例路徑,如果您在/usr/bin/etc//first/dir/to/delete或其他任何完全不符合其父系的地方,它將默認為您的路徑。 如果您在/first/dir/to/edit/today ,它將匹配/first/dir/to/edit作為父級(該路徑的任何子目錄)並使用/opt/homebrew/Cellar/php@8.0/8.0.26/bin/php 如果您在/next/dir/for/lunch中,它將匹配/next/dir作為父級並使用/some/other/version/bin/php ,但在/next/dir/for/edits中,它匹配較長的路徑首先使用/opt/homebrew/Cellar/php@8.0/8.0.26/bin/php代替。

希望所有這些都有助於激發一個有用的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM