跳到正文
DEV Community· Vitalii Shumylo·· 1 小時前AI 評分34

Bash 函數為何把 300 GB 説成 44 GB:return 不能傳回資料

A bash function said 44 when the folder held 300 GB: return is not for data

AI 導讀

Bash 函數的 return 設定的是退出狀態,不是傳回資料;狀態值只限 0 至 255,因此 300 會變成 44。要取得數值,可讓函數把結果輸出至標準輸出,再由呼叫端擷取;提示訊息則輸出至標準錯誤,並用 local 限定函數內的變數。

正文

Vitalii Shumylo

You write a small bash function that counts how many gigabytes a folder uses. It ends with return $size, and the caller reads the number from $?. On a test machine it looks fine. Then on a real server the script reports 44 GB for a folder that holds 300 GB.

The cause is what return really does. It does not send data back. It sets the exit status of the function, and an exit status can only be a number from 0 to 255. Bigger numbers wrap around, so 300 becomes 44. The status has one job: 0 for success, any other number for failure. There is a second trap close by. A variable that you set inside a function without local changes the variable with the same name in the rest of the script.

The fix is to print the value and catch the output:

folder_gb() {
    local kb
    echo "Checking $1" >&2
    kb=$(du -sk "$1" | cut -f1)
    echo $(( kb / 1024 / 1024 ))
}

size=$(folder_gb /srv/data)
echo "/srv/data uses ${size} GB"

$(...) collects everything that the function prints to standard output. For this reason, the function prints only the number. The message for the user goes to standard error with >&2, so it stays out of the result. local keeps kb inside the function.

The full guide shows how to define and call a function, and how its arguments differ from the arguments of the script. It tests a status with if. It shows local with its output, so you can see the difference. It builds a small set of helpers for admin scripts: log, die and need. It also fixes the "command not found" error that you get when you call a function before you define it.

Read the full guide: https://learnitlessons.com/articles/bash-functions-examples/

Written with AI assistance and checked by the author.

Free PDF checklist (Group Policy is not applying): https://learnitlessons.com/go/free-gpo?s=devto - and free seats and coupons first on Telegram: https://t.me/itcoursesdeals

來源:DEV Community · dev.to