1

What does this line of code mean

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

I can't seem to understand it.

2
  • 1
    What specific part of it is unclear? (If the answer is "everything", please start with explainshell, what is eval and what is -n) Commented May 2, 2018 at 17:54
  • 3
    It's a particularly dangerous way to create a variable dynamically, but providing a better alternative would require more context about where this code is executed. Commented May 2, 2018 at 17:55

1 Answer 1

1

[ -n "$var" ] evaluates to true (i.e. return exit status 0) if the length of $var is non-zero. Also cmd1 && cmd2 executes cmd2 only if cmd1 returns an exit status of zero. And cmd1 && cmd2 executes cmd2 only if cmd1 returns a non-zero exit status. Perhaps an example can help illustrate what your code is doing:

#!/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                                                           
Sign up to request clarification or add additional context in comments.

5 Comments

it is $var=\$local_var and $var='$'local_var the same statement isn't it?
Both forms give the same output (so does $var="$"local_var). But I had only seen $var=\$local_var used before.
@D'ArcyNader They're equivalent, just different ways of suppressing the special meaning of $ on the first parsing pass. $var='$local_var' or even $var'=$local_var' would work as well.
@Sergio how does eval $var=\$local_var === foo=$local_var
@FayVor eval is a builtin command described in man bash: "The args are read and concatenated together into a single command. This command is then read and executed by the shell". I'd suggest reading: unix.stackexchange.com/a/23117/281661

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.