0

why does the below script print empty for the shell variables The expected output is "encapsulated-options 10.1.42.35:4334" but it prints "encapsulated-options : ;" . Please advise.

#!/bin/bash                                                                    
cem_ip=""                                                                      
cem_port=""                                                                    
DHCPDCONF="encapsulated-options \"$cem_ip:$cem_port\";";                       

function print()                                                               
{                                                                              
    cem_ip="10.1.42.35";                                                       
    cem_port=4334;                                                             
    echo -e "$DHCPDCONF"                                                       
    return 0;                                                                  
}                                                                              

print;            
Ravikumar Tulugu
  • 1,702
  • 2
  • 18
  • 40

1 Answers1

0

You seem to think of bash variables as object which can be passed by reference. But it's not like that.

By the time you concatenate the variables cem_ip and cem_port into a string and save it in variable DHCPDCONF. The values (empty string) of those vars are used as is at that very moment.

The DHCPDCONF variable is now just a string and does not know it was assembled from two other vars. When you later change the values of the cem_* variables, the DHCPDCONF value won't change

#!/bin/bash
cem_ip="";
cem_port="";

function encapsulated_options () {
    echo "encapsulated-options \"${1}:${2}\";";
}

function print () {
    cem_ip="1.2.3.4";
    cem_port="5678";
    DHCPDCONF=$(encapsulated_options "${cem_ip}" "${cem_port}");
    echo -e $DHCPDCONF;
}

print;
yunzen
  • 32,854
  • 11
  • 73
  • 106
  • But instead of shell variables , if i use environment variables , it is working – Ravikumar Tulugu Apr 04 '19 at 02:54
  • It all boils down to the point: When do you assemble the value of the `DHCPDCONF` variable and what values do the variables `cem_ip` and `cem_port` have at that very moment – yunzen Apr 04 '19 at 07:08