[英]Bash - problem with using unset variable in a script
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. 问题在于,在设置
ANOTHER_VARs
后设置VAR1
会使它们的路径没有VAR1
部分。 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. 我不能将
getopts
移到那些之上,因为脚本很长,并且有很多方法取决于变量和其他方法。 Any ideas how to solve this? 任何想法如何解决这个问题?
I'd make ANOTHER_VAR and ANOTHER_VAR_2 into functions. 我要把ANOTHER_VAR和ANOTHER_VAR_2变成函数。 The return value would depend on the current value of VAR1.
返回值取决于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)
然后,您将使用
$(ANOTHER_VAR)
而不是$ANOTHER_VAR
Is it possible to set the ANOTHER_VAR and ANOTHER_VAR_2 variables below where getopts
is called? 是否可以在调用
getopts
下面设置ANOTHER_VAR和ANOTHER_VAR_2变量? Also, how about setting the ANOTHER_VAR and ANOTHER_VAR_2 in a function, that's called after getopts? 另外,如何在getopts之后调用的函数中设置ANOTHER_VAR和ANOTHER_VAR_2?
foobar(){
do something
return
}
foobar()
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. 在设置ANOTHER_VAR之前,不能使用“取决于变量的许多方法”,因此您只需将定义移至
getopts
循环之后即可。
One advantage of shell scripts is that variables do not have to be defined before the functions that use them are defined; Shell脚本的一个优点是,在定义使用它们的函数之前不必定义变量。 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".) (也就是说,这样做并不是很不错的样式,但是会使您陷入困境。您还应该能够将
getopts
循环移到函数上方,这样会更好。您可以在您无法通过“我不能将getopts
移到那些之上之前”进行很多解释。)
So, your fixes are (in order of preference): 因此,您的修复是(按优先顺序):
getopts
loop. getopts
循环。 getopts
loop and before you invoke any function that depends on them. getopts
循环之后和调用任何依赖它们的函数之前,将设置ANOTHER_VAR和ANOTHER_VAR_2的两行移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.