bikerben
bikerben

Reputation: 483

Bash shell variable inside variables

I'm pretty sure this can be done but I'm not quite sure what the correct syntax is:

dev=$(someprog1 -flag -flag);
tpcli=$(someprog2 -flag);
if [[ $tpcli = $(someprog3 -flag $dev -flag | grep stuff | cut -c 25-55) ]]; then
blah;
blah;

Basically I want to create the variable and add it inside a variable in side the IF statement. Any help would be greatly appreaciated.

Upvotes: 0

Views: 1140

Answers (2)

Dirk-Willem van Gulik
Dirk-Willem van Gulik

Reputation: 7706

That generally works; e.g. try

P=$(echo $PATH)

when in doubt - use the ${PATH} braces and/or escaped "'s - as to control a single argument with spaces or something which is expanded; and has its spaces seen as separators between arguments. (Which is by the way not needed in your example if we assume that we have no filenames and what not with spaces in them).

As a larger example - consider:

  #!/bin/sh
  dev=$(echo /dev/null)
  if [ $(cat $dev | wc -l) = "0" ]; then
      echo Fine
    exit 0
  else
      echo Now that is a surprize
  fi
  exit 1

which when ran gives us

  beeb-2:~ dirkx$ sh xx.sh
  Fine

or more elaborate:

  beeb-2:~ dirkx$ sh -x xx.sh
  ++ echo /dev/null
  + dev=/dev/null
  ++ cat /dev/null
  ++ wc -l
  + '[' 0 = 0 ']'
  + echo Fine
  Fine
  + exit 0

so that should help you find the issue. You sure there is not some space or transposition ?

Upvotes: 0

bos
bos

Reputation: 6555

I'm not quite sure what you're asking, but there's nothing wrong with what you've done (except that I would never have a subshell within an if-clause).

bos@bos:$ foo=42
bos@bos:$ [ $foo = $(echo 42) ] && echo yes || echo no
yes
bos@bos:$ [ $foo = $(echo 242) ] && echo yes || echo no
no

Upvotes: 1

Related Questions