如何讓 bash 轉換「~」?

如何讓 bash 轉換「~」?

某些程式無法識別檔案名稱中的波形符號捷徑,並需要完整的規範路徑,例如/home/dave/myfile.txt而不是~/myfile.txt.

有沒有辦法讓 bash在使用波浪號時替換為完整的規範路徑~~user

答案1

好吧,不確定 perl,但在 bash 腳本中你可以使用 eval 進行轉換:

eval dir='~user/somedir'

$dir 將包含完整路徑,即 /home/user/somedir 此時。

答案2

當您在 Bash shell 中執行命令時,例如:

command ~/myfile.txt

shell 首先進行擴充~(除非被引用),然後使用結果執行指令。

但確實,有些程序不解釋~,例如:

$ cat "~/myfile.txt"
~/myfile.txt: No such file or directory

但這有效:

nano "~/myfile.txt"

但這種行為被 Bash 擴展掩蓋了,所以你不需要任何進一步的解釋

也許這是顯而易見的,但請注意,如果程式使用設定檔並期望其中包含某些路徑,則 Bash 不負責擴展它們。

相關內容