如何在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 fromoutput.txtimmediately afterscript.shhas updated it. - Using
bcfor decimal comparisons: Bash’s built-in operators only work with integers. Thebccommand evaluates the floating-point expression and returns 1 if true, 0 if false—perfect for our check. - Running
script.shfirst in the loop: Guaranteesoutput.txtis 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
相关产品推荐
相关产品推荐

