2017-07-07 31 views
1

我試圖在bash腳本中執行diff命令時出現一個非常令人驚訝的問題。當提供一個包含代字號的路徑變量時,bash diff無法找到現有文件(〜)

這裏是工作的代碼說明了這一點:

#!/bin/bash 
cd 
mkdir foo bar 
head -c 1024 /dev/urandom >foo/qux 
head -c 1024 /dev/urandom >bar/qux 

# works properly as expected 
diff ~/{foo,bar}/qux 

folder="~" 

# this fails with the ~ inside a variable 
diff $folder/{foo,bar}/qux 

# cleaning the mess 
rm -rf foo bar 

所以我的問題是:

爲什麼? :-)

回答

1

將其分配給變量時,不要引用~。當你不引用它時,~只會被bash擴展。

+0

haha​​haha :)非常感謝你 –

1

〜是shell擴展的一個特性。
雙引號限制擴大到只有三個特點:

  1. 命令替換:$(命令)| `命令...'
  2. 變量替換:$ VAR | $ {VAR}
  3. 算術:$((2 + 2))
+0

這並不一定解釋爲什麼'$文件夾'(未加引號)不會擴展代字號。 – chepner

+0

你是什麼意思?請舉個例子。 – hedgar2017

0

波浪線擴展僅適用於無引號波浪號。在執行賦值至folder時,必須擴展波形符號,因爲波形符號擴展不適用於參數擴展,僅適用於字詞拆分和路徑名擴展。

folder=~ # ~ is expanded, and the result is assigned to folder