Piyushkumar Patel
Piyushkumar Patel

Reputation: 199

Bash call variables in for loop variables

I am curious to know that whether it is possible in bash that we can run for loop on a bunch of variables and call those values within for loop. Example:

a="hello"
b="world"
c="this is bash"

for f in a b c; do {
  echo $( $f )
OR
  echo $ ( "$f" )
} done

I know this is not working but can we call the values saved in a, b and c variables in for loop with printing f. I tried multiple way but unable to resolve.

Upvotes: 0

Views: 1913

Answers (3)

agc
agc

Reputation: 8406

Notes on the OP's code, (scroll to bottom for corrected version):

for f in a b c; do {
  echo $( $f )
} done

Problems:

  1. The purpose of { & } is usually to put the separate outputs of separate unpiped commands into one stream. Example of separate commands:

    echo foo; echo bar | tac
    

    Output:

    foo
    bar
    

    The tac command puts lines of input in reverse order, but in the code above it only gets one line, so there's nothing to reverse. But with curly braces:

    { echo foo; echo bar; } | tac
    

    Output:

    bar
    foo
    

    A do ... done already acts just like curly braces.
    So "do {" instead of a "do" is unnecessary and redundant; but it won't harm anything, or have any effect.

  2. If f=hello and we write:

    echo $f
    

    The output will be:

    hello
    

    But the code $( $f ) runs a subshell on $f which only works if $f is a command. So:

    echo $( $f )
    

    ...tries to run the command hello, but there probably is no such command, so the subshell will output to standard error:

    hello: command not found
    

    ...but no data is sent to standard output, so echo will print nothing.


To fix:

a="hello"
b="world"
c="this is bash"

for f in "$a" "$b" "$c"; do
  echo "$f"
done

Upvotes: 0

Shawn
Shawn

Reputation: 52334

You can also use a nameref:

#!/usr/bin/env bash

a="hello"
b="world"
c="this is bash"

declare -n f
for f in a b c; do 
  printf "%s\n" "$f"
done

From the documentation:

If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed.

Upvotes: 2

Walter A
Walter A

Reputation: 19982

You need the ! like this:

for f in a b c; do
  echo "${!f}"
done

Upvotes: 3

Related Questions