Issue
How can I use the stdout of the echo command as an argument in a for loop.
echo NUMBER | for i in {1..$NUMBER}; do if [ $(( $i % 2 )) -eq 0 ]; then echo "even"; fi; done
In this example, I wish to loop over a sequence of numbers with a length equal to the integer outputted by echo. How can I do this in a single command line?
Solution
The list for a for
loop cannot read from standard input. However, you can't combine brace expansion and parameter expansion like this in the first place (a common mistake).
Use a C-style for loop instead, setting the value of NUMBER
however you like prior to the loop.
read NUMBER # reads from standard input
for ((i=1; i <= $NUMBER; i++)); do
...
done
This also lets you skip the repeated division in your original question. Instead of filtering the even numbers from the full range, just generate only the even numbers.
for ((i=2; i <= $NUMBER; i+= 2)); do
echo even
done
Answered By - chepner Answer Checked By - Candace Johnson (WPSolving Volunteer)