If I run the
echo {0..9}
command, then I get the following output:
0 1 2 3 4 5 6 7 8 9
Can I somehow put the string "0 1 2 3 4 5 6 7 8 9"
into a variable inside bash
script? I only found a way using echo
:
x=`echo {0..9}`
But this method implies the execution of an external program. Is it possible to somehow manage only with bash
?
Interested, rather than a way to convert a range to a string, but additionally concatenate with a string, for example:
datafiles=`echo data{0..9}.txt`
CodePudding user response:
First of all,
x=`echo {0..9}`
doesn't call an external program (echo
is a built-in) but creates a subshell. If it isn't desired you can use printf
(a built-in as well) with -v
option:
printf -v x ' %s' {0..9}
x=${x:1} # strip off the leading space
or
printf -v datafiles ' data%s.txt' {0..9}
datafiles=${datafiles:1}
or you may want storing them in an array:
datafiles=(data{0..9}.txt)
echo "${datafiles[@]}"
This last method will work correctly even if filenames contain whitespace characters:
datafiles=(data\ {0..9}\ .txt)
printf '%s\n' "${datafiles[@]}"