So I'm trying to do something, not sure if it's possible. I have the following code:
for i in {0..5}; do
if [[ -f ./user$i ]]; then
group$i=$(grep -w "group" ./user0|awk '{print $2}'|perl -lape 's/\s+//sg')
What I want to do is assign a unique variable for each instance of the {0..5} so group1 group2 group3 group4 for each variable name. Then I would change ./user0 to ./user$i and create a dynamic list of variables based on my sequence. Is this possible? I get the following error when trying to execute this and I'm unsure of what I have actually done that bash doesn't like.
test.sh: line 16: group0=j: command not found
Try to use the export or declare function like this
with declare
where
export
makes the value available to sub-processes, anddeclare
just available within the same script.Use
declare group$i=...
instead of justgroup$i=...
Kurt Stutsman provides the right pointer in a comment on the question: use Bash arrays to solve your problem.
Here's a simplified example:
See the bottom of this answer for other ways to enumerate the elements of array
${groups[@]}
.bash
arrays can be dynamically expanded (and can even be sparse - element indices need not be contiguous)$i
works, without prior sizing of the array.Note how
$i
need not be prefixed with$
in the array subscript, because array subscripts are evaluated in an arithmetic context (the same context in which$(( ... ))
expressions are evaluated).As for what you did wrong:
is not recognized as a variable assignment by Bash, because - taken literally -
group$i
is not a valid identifier (variable name).Because it isn't, Bash continues to parse until the next shell metacharacter is found, and then interprets the resulting word as a command to execute, which in your case resulted in error message
group0=j: command not found
.If, for some reason, you don't want to use arrays to avoid this problem entirely, you can work around the problem:
By involving a variable-declaring builtin [command] such as
declare
,local
, orexport
, you force Bash to perform expansions first, which expandsgroup$i
to a valid variable name before passing it to the builtin.user2683246's answer demonstrates the next best approach by using
declare
(or, if local variables inside a function are desired,local
) to create the variables.Soren's answer uses
export
, but that is only advisable if you want to create environment variables visible to child processes rather than mere shell variables.Caveat: With this technique, be sure to double-quote the RHS in order to capture the full value; to illustrate:
Other ways to enumerate the
groups
array created above: