assign local variable from function in linux bash a new value assign local variable from function in linux bash a new value bash bash

assign local variable from function in linux bash a new value


Once you've defined a local variable you can assign it normally, like this:

#!/bin/bashmyfunctiona () {  local MYVAR1="one"  local MYVAR2="two"  echo $MYVAR1  # The line beneath is the line in question!  local MYVAR1=$MYVAR1$MYVAR2      MYVAR1="FOO"  echo $MYVAR1   }myfunctionaecho "global" $MYVAR1

which gives the output:

oneFOOglobal
  • As you can see attempting to access the variable from global scope returns null

HTH


The correct way to do it would be:

MYVAR1="${MYVAR1}${MYVAR2}"

The braces are usually used when you concatenate variables. Use quotes.

The variable is still local since you reassigned its value within the scope of the function.An example:

#!/usr/bin/env bash_myFunction(){    local var_1="one"    local var_2="two"    local -g var_3="three" # The -g switch makes a local variable a global variable    var_4="four" # This will be global since we didn't mark it as a local variable from the start    var_1="${var_1}${var_2}"    echo "Inside function var_1=${var_1}"    echo "Inside function var_2=${var_2}"    echo "Inside function var_3=${var_3}"    echo "Inside function var_4=${var_4}"}_myFunctionecho "Outside function var_1=${var_1}"echo "Outside function var_2=${var_2}"echo "Outside function var_3=${var_3}"echo "Outside function var_4=${var_4}"

This results in:

$ ./scriptInside function var_1=onetwoInside function var_2=twoInside function var_3=threeInside function var_4=fourOutside function var_1=Outside function var_2=Outside function var_3=threeOutside function var_4=four


You can give this way, but as Ube said for concatenation you need to give like that -

MYVAR1="$MYVAR1$MYVAR2";   

Even this works for concatenation