Bash使用函数编写脚本

时间:2018-05-02 17:44:45

标签: bash shell

这行代码意味着什么

[ -n "$local_var" ] && eval $1=\$local_var

我似乎无法理解它。

1 个答案:

答案 0 :(得分:1)

如果[ -n "$var" ]的长度不为零,则

0计算结果为true(即返回退出状态$var)。仅当cmd1 && cmd2返回退出状态为零时,cmd2才会执行cmd1。仅当cmd1 && cmd2返回非零退出状态时,cmd2才会执行cmd1。也许一个例子可以帮助说明你的代码在做什么:

#!/usr/bin/env bash                                                             

# $local_var has not been initialized so has length zero                                                                               
[ -n "$local_var" ] || echo '$local_var' has zero length                        
# Prints: $local_var has zero length                                            

var=foo                                                                         
local_var=bar                                                                   

[ -n "$local_var" ] && eval $var=\$local_var                                    
# Above line is equivalent to:                                                  
# [ -n "$local_var" ] && foo=$local_var                                         
echo "$var $foo $local_var"                                                     
# Prints: foo bar bar