PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] How to use a bash variable reference to an associative array in a bash function without declaring it before calling that function?

 July 05, 2022     arrays, associative-array, bash, pass-by-reference     No comments   

Issue

There are multiple ways to get a result from a function in a bash script, one is to use reference variables like local -n out_ref="$1, which is also my preferred way.

My bash version is:

GNU bash, Version 5.0.3(1)-release 

Recently, one of my bash functions needed to produce a associative array as a result, like in this example code:

#!/bin/bash

testFunction() {
    local -n out_ref="$1"

    out_ref[name]="Fry"
    out_ref[company]="Planet Express"
}

declare -A employee
testFunction employee

echo -e "employee[name]: ${employee[name]}"
echo -e "employee[company]: ${employee[company]}"

I declare the variable employee as an associative array with declare -A.

The output is:

employee[name]: Fry
employee[company]: Planet Express

If I remove the line declare -A employee, the output is:

employee[name]: Planet Express
employee[company]: Planet Express

Is there a way to move the declaration of the associative array into the function, so the user of that function does not need to do it beforehand?


Solution

Use declare -Ag "$1" inside the function, so that you declare employee as a global variable.



Answered By - Niloct
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing