[問題] Shell script 計算total used space

看板LinuxDev作者 (chemadent)時間12年前 (2013/03/06 20:33), 編輯推噓0(005)
留言5則, 1人參與, 最新討論串1/1
如題,我想用shell script計算df產生之total used space, 但不使用df --total 以下是我的code(看起來很不shell script@@) 我用很奇怪的方法才只印出我要的那個數值,有沒有什麼比較優的寫法? 另外,想問awk裡面能使用在awk外面宣告的變數嗎? 比如說在df那行之前有 ans=0 然後想在awk裡面使用ans紀錄最後的數值,再印出來ans 懇請各位大大解惑 m(__)m #! /bin/bash #Program: # Try to calculate the total used space without using cmd: "df --total" df | awk 'NR==1{total = 0};NR>=2{total = (total + $3)};{print total}' | sed -n '$p' exit 0 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.229.66.69 ※ 編輯: Carlchen 來自: 220.229.66.69 (03/06 21:43) ※ 編輯: Carlchen 來自: 220.229.66.69 (03/06 21:45) ※ 編輯: Carlchen 來自: 220.229.66.69 (03/06 22:05)

03/07 02:21, , 1F
df | awk 'BEGIN{total=0}NR>=2{total += $3}
03/07 02:21, 1F

03/07 02:21, , 2F
END{print total}'
03/07 02:21, 2F

03/07 02:23, , 3F
ans=789 ; awk -v a=${ans} 'BEGIN{print a+1}'
03/07 02:23, 3F

03/07 02:28, , 4F
ans=$(awk -v a=${ans} 'BEGIN{print a+1}')
03/07 02:28, 4F

03/07 02:28, , 5F
echo $ans
03/07 02:28, 5F
文章代碼(AID): #1HDpUrH9 (LinuxDev)
文章代碼(AID): #1HDpUrH9 (LinuxDev)