bash - Bash 函数 | 更新变量而不在终端中回显
问题描述
我有一个名为 freespace_function 的函数,我使用此函数在脚本执行时更新 $free_disk_space 变量。我遇到的问题是每次我在脚本中调用该函数时,它都会在终端中回显该值。我无法删除函数中的回声,否则它的输出为零。我只希望函数静默执行(更新 free_disk_space)而不在终端中提供输出。
freespace_function () {
local function_result="$(df -m "${destination}" | tail -1 | awk '{print $4}')"
echo "${function_result}"
free_disk_space=$(freespace_function)
}
# inner loop
while [[ "${free_disk_space}" -lt "${source_size}" ]] ; do
echo "${free_disk_space} MB is not enough free space"
read -r -n 1 -p "please create free disk space to continue..."
freespace_function
if [[ "${free_disk_space}" -gt "${source_size}" ]] ; then
# breaks out of the inner loop when the if free space condition is true
break
fi
done
解决方案
所以我认为你需要重新设计你的函数,使它不使用变量赋值。像这样的东西
freespace_function () {
# it's a better practice to explicitly pass parameters to functions instead of relying on globals
local destination=$1
echo "$(df -m ${destination} | tail -1 | awk '{print $4}')"
}
# re-evaluates but won't print
# notice that the condition is evaluating on the result of a sub-shell instead of a variable
while [[ "$(freespace_function /tmp/dir)" -lt "${source_size}" ]] ; do
echo "${free_disk_space} MB is not enough free space"
read -r -n 1 -p "please create free disk space to continue..."
# no need to explicitly break out of the loop
done
推荐阅读
- c++ - C++ 链表 HEAD 不断重置为 NULL
- php - 使用数组索引(不是键)手动 Laravel 验证
- cuda - 为什么 cudaOccupancyMaxActiveBlocksPerMultiprocessor() 独立于设备?
- servicenow - 立即服务 - 如何使用 OAuth2 对其他帐户(服务器)进行身份验证
- css - 带空白的 CSS 对角渐变
- python - 雅虎财经 下载具体数据 Python PE
- api - 有没有办法克隆 API?
- delphi - 组件代码中的 TThread -Delphi 7
- javascript - (节点:12752)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“byteLength”
- python - 在没有 root 或影响全局包的情况下在 python3.6 venv 中升级 SQLite 版本