首页 > 解决方案 > 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

标签: bash

解决方案


所以我认为你需要重新设计你的函数,使它不使用变量赋值。像这样的东西

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

推荐阅读