up vote 0 down vote favorite
share [g+] share [fb]

I have following code:

VAR1=""
ANOTHER_VAR="$VAR1/path/to/file"
ANOTHER_VAR_2="$VAR1/path/to/another/file"

...

# getopts which reads params from command line and sets the VAR1

The problem is that setting the VAR1 after ANOTHER_VARs are set makes their paths without the VAR1 part. I can't move the getopts above those because the script is long and there are many methods which depends on the variables and on other methods. Any ideas how to solve this?

link|improve this question

1  
Can you move the ANOTHER_VAR and ANOTHER_VAR_2 below the getopts instead? – sbtkd85 Aug 22 '11 at 15:17
1  
@sbtkd85 He does explicitly say that he can't do that, but equally, I don't understand why on earth that would be. Can you post some more code/a better explaination of why exactly you can't change the order of the operations? – DaveRandom Aug 22 '11 at 15:20
@DaveRandom The script has over 500 lines and many functions which need the variables and getopts need those functions so the order must be: variables, functions, getopts. The order cannot be simply changed. – Tomas Aug 23 '11 at 9:20
feedback

3 Answers

up vote 3 down vote accepted

I'd make ANOTHER_VAR and ANOTHER_VAR_2 into functions. The return value would depend on the current value of VAR1.

ANOTHER_VAR () { echo "$VAR1/path/to/file"; }
ANOTHER_VAR_2 () { echo "$VAR1/path/to/another/file"; }

Then, instead of $ANOTHER_VAR, you'd use $(ANOTHER_VAR)

link|improve this answer
Great solution. Thank you! – Tomas Aug 23 '11 at 9:10
feedback

Is it possible to set the ANOTHER_VAR and ANOTHER_VAR_2 variables below where getopts is called? Also, how about setting the ANOTHER_VAR and ANOTHER_VAR_2 in a function, that's called after getopts?

foobar(){
  do something
  return
}
foobar()
link|improve this answer
feedback

Your 'many methods which depend on the variables' cannot be used before you set ANOTHER_VAR, so you can simply move the definitions to after the getopts loop.

One advantage of shell scripts is that variables do not have to be defined before the functions that use them are defined; the variables merely have to be defined at the time when the functions are used. (That said, it is not dreadfully good style to do this, but it will get you out of the scrape you are in. You should also be able to move the getopts loop up above the functions, which would be better. You have a lot of explaining to do before you can get away with "I can't move the getopts above those".)

So, your fixes are (in order of preference):

  1. Move the getopts loop.
  2. Move the two lines that set ANOTHER_VAR and ANOTHER_VAR_2 after the getopts loop and before you invoke any function that depends on them.
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.