You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash循环中动态刷新变量$A0,满足条件后执行script2.sh?

Fixing the Dynamic Value Update in Your Loop

The core issue here is that you’re assigning $A0 outside your while loop—so it only grabs the initial value from output.txt once, and never refreshes it. To get the latest value every time the loop runs, you need to re-read the file and update $A0 inside the loop, right after script.sh has generated fresh output.

Here’s a corrected script structure that fixes this:

#!/bin/bash

while true; do
    # First, run script.sh to generate the latest output.txt
    ./script.sh

    # Now read the updated value from output.txt into A0
    A0=$(cat output.txt)

    # Bash can't handle floating-point comparisons natively, so use bc for the check
    if (( $(echo "$A0 > 2.37" | bc -l) )); then
        ./script2.sh
        # Optional: Uncomment below to exit the loop after running script2.sh
        # break
    fi

    # Add a delay to avoid spamming the loop (adjust duration as needed)
    sleep 1
done

Key Fixes Breakdown:

  • Moving A0=$(cat output.txt) inside the loop: This ensures every iteration pulls the most recent value from output.txt immediately after script.sh has updated it.
  • Using bc for decimal comparisons: Bash’s built-in operators only work with integers. The bc command evaluates the floating-point expression and returns 1 if true, 0 if false—perfect for our check.
  • Running script.sh first in the loop: Guarantees output.txt is fresh before we read its value each time.

Quick Alternate Tip:

If script.sh outputs the value directly to stdout instead of writing to a file, you can skip output.txt entirely and capture the value directly:

A0=$(./script.sh)

内容的提问来源于stack exchange,提问作者Grim Edge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:23:59