2016-10-01 80 views
1

我在我的bashrc文件中有一個別名,用於輸出當前文件夾內容和系統可用存儲,並通過watch函數不斷更新。在bash腳本中需要幫助從awk引用轉義

alias wtch='watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | awk '{print \$4}'"' 

該字符串工作正常,直到我把awk部分。我知道我需要避開單引號,同時仍然留在雙引號和$ 4中,但是我一直無法使其工作。我究竟做錯了什麼?

這是錯誤我得到

-bash: alias: $4}": not found 

回答

2

在這種情況下,你可以使用cut,而不是awk。你會有同樣的效果。

alias wtch="watch -n 0 -t 'du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | cut -d\ -f4'" 

解釋cut

-d option defines a delimiter 
-d\ means that my delimiter is space 
-f selects a column 
-f4 gives you the fourth column 
4

由於對別名的引用是使它艱難的,你可以只讓一個函數:

wtch() { 
    watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | awk '{print $4}'" 
} 

這是很多像問題2在BashFAQ/050

此外,一個小事情,但你可以跳過在結束head過程,只是有awk做到這一點,在第二行後甚至退出像

wtch() { 
    watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| awk '{print $4} NR >= 3 {exit}'" 
} 
+1

@EdMorton再次感謝埃德!我一如既往地採納了你的建議(主要是) –