Is it possible to do something like this:
start=1
end=10
echo {$start..$end}
# Ouput: {1..10}
# Expected: 1 2 3 ... 10 (echo {1..10})
Is it possible to do something like this:
start=1
end=10
echo {$start..$end}
# Ouput: {1..10}
# Expected: 1 2 3 ... 10 (echo {1..10})
In bash, brace expansion happens before variable expansion, so this is not directly possible.
Instead, use an arithmetic for
loop:
start=1
end=10
for ((i=start; i<=end; i++))
do
echo "i: $i"
done
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10
start=1;end=10;for i in $(bash -c "echo {$start..$end}");do echo $i;done
–
Northwest You should consider using seq(1)
. You can also use eval:
eval echo {$start..$end}
And here is seq
seq -s' ' $start $end
dash
maybe ? Or ash
? Or tcsh
? –
Tref ports
). –
Tref eval
is as horrid here as in most other places, don't get used to it or you'll find yourself leaving command injection vulnerabilities some day –
Cooe eval echo {$((start))..$((end))}
–
Client $((var))
is not safe if the value of var
has not been sanitized. See Security Implications of using unsanitized data in Shell Arithmetic evaluation. –
Horwath You have to use eval
:
eval echo {$start..$end}
for ((i=start; i<end; i++)); do ...; done
. –
Timbering If you don't have seq
, you might want to stick with a plain for loop
for (( i=start; i<=end; i++ )); do printf "%d " $i; done; echo ""
I normally just do this:
echo `seq $start $end`
seq
is a non-standard tool (literally, not specified in POSIX). –
Timbering seq
is non-standard, but the echo + command substitution is just a silly combination. –
Cooe IFS
is changed from the default). So you get the numbers all on the same line, not one line each like the default with seq
. But if you want that, you could just use seq -w ' ' 1 10
. If you do quote the command substitution, on the other hand, then echo "$(seq 1 10)"
and seq 1 10
have exactly the same output. Command substitution strips trailing newlines (there's one), and echo
adds one back. –
Cooe Are you positive it has be BASH? ZSH handles this the way you want. This won't work in BASH because brace expansion happens before any other expansion type, such as variable expansion. So you will need to use an alternative method.
Any particular reason you need to combine brace and variable expansion? Perhaps a different approach to your problem will obviate the need for this.
use -s ex: seq -s ' ' 1 10 output: 1 2 3 4 5 6 7 8 9 10
© 2022 - 2024 — McMap. All rights reserved.