bash loop trough variables

if i have a bunch of variables in bash:

foo_1="path/1"
foo_2="path/2"
foo_3="path/3"
foo_4="path/4"
foo_5="path/5"

They all start with foo_. Is there a way to loop trough them, and run a command on each of them? I tryed it with regex

for i in [ $foo_.\+ ]

but that seems not to work.

For example if I want to run mkdir on all variables starting with foo_, how would i do that?

2 Answers

I agree wholeheartedly with @choroba's advice: dynamically-named variable names are a PITA to work with.

Nevertheless, there is a way with some special syntax:

for var in "${!foo_@}"; do declare -n ref=$var mkdir -p "$ref"
done

results in

$ tree
.
└── path ├── 1 ├── 2 ├── 3 ├── 4 └── 5
6 directories, 0 files

3.5.3 Shell Parameter Expansion in the manual says:

${!prefix*}
${!prefix@}

Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When ‘@’ is used and the expansion appears within double quotes, each variable name expands to a separate word.

and declare documents:

declare [-aAfFgiIlnrtux] [-p] [name[=value] …]

-n

Give each name the nameref attribute, making it a name reference to another variable. That other variable is defined by the value of name. All references, assignments, and attribute modifications to name, except for those using or changing the -n attribute itself, are performed on the variable referenced by name’s value. The nameref attribute cannot be applied to array variables.

0

Use an array instead.

foos=(path/1 path/2 path/3 path/4 path/5)

To make all the directories, you can then

mkdir -p "${foos[@]}"

Or, if you want to do something one by one

for foo in "${foos[@]}" ; do mkdir -p "$foo"
done

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like