bash return associative array from function
23963
post-template-default,single,single-post,postid-23963,single-format-standard,ajax_fade,page_not_loaded,,select-theme-ver-4.2,wpb-js-composer js-comp-ver-5.4.4,vc_responsive

bash return associative array from function

Copying associative arrays is not directly possible in bash. Internal. If someone knows a better way, feel free to add it here. After some bash self study and experimenting, I am stuck with returning an array from a function, and for the life of me can't see my error. assign the function's return array to array clients, while the function executes, add values DIRECTLY to the clients array. What can we do with other data in a function that we want to use in another function / context? Could the US military legally refuse to follow a legal, but unethical order? There is another solution which I used to pass variables to functions. We can loop through the associative array in two ways. :-). Any third year CS major should know that. To learn more, see our tips on writing great answers. First by using for loop and secondly by using foreach. Some are satisfied with converting a list to a string and calling it a day, but if you truly want to deal with an official bash array, the here sting above will do that for you. Yes you can, but you must use a typedef to define the return type. : It is worth mentioning that array initialization using this bracket form initializes the new array according to the IFS or Internal Field Separator which is by default tab, newline and space. An associative array can be thought of as a set of two linked arrays -- one holding the data, and the other the keys that index the individual elements of the data array. Bash associative array tutorial; Bash check if file begins with a string; Bash shell - check if file or directory exists; Can global variables be modified in bash function? This article will cover some ways you can return values from bash functions: Return value using global variable. function return values. What specifically is your concern about the script being "easily modified" here? Copying associative arrays is not directly possible in bash. Associative arrays (sometimes known as a "hash" or "dict") use arbitrary nonempty strings as keys. Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. They decided that ${array} was just short hand for ${array[0]}, which was a bad mistake. Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. Here is sample code to demonstrate it. This is passing, in essence, nothing by value - as usual. For more serious scripts, consider as mentioned, putting the keys in its own array, and search it while looking up values. The order of march would be. Bash Return Multiple Values from a Function using an Associative Array. Unix & Linux: bash silently does function return on (re-)declare of global associative read-only arrayHelpful? It also makes it so that you can create sparse numerically indexed arrays. If I call doSomething, it might, say, send a string message to stdout. As such, to pass an array to a function, there is really only one option, and that is to use the nameref feature: Since this is passing by reference, you can also assign to the array in the function. Why is "I can't get any satisfaction" a double-negative too, according to Steven Pinker? In short, what this should/must do is by using a function The method I developed allows you to access parameters passed to a function like this: In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. When it comes to functions in bash, one topic that often comes is returning values.There are many different things that you may return from a function, return values, exit codes, or nothing at all. ... Posted by 22 days ago. Is there in bash an array_combine function, where I can create an associative array from two? You can pass multiple arrays as arguments using something like this: arrays - script - bash pass associative array to function, Getting the source directory of a Bash script from within, How to check if a string contains a substring in Bash. But because they didn't do this right, the assignment operator = doesn't work for arrays, and arrays can't be passed by value to functions or to subshells or output in general (echo ${array}) without code to chew through it all. In other words, you can return from a function with an exit status. In these cases, I've had to first determine and then remove the parameters not associated with the array using some combination of shift and array element removal. You can also initialize an entire associative array in a single statement: aa=([hello]=world [ab]=cd ["key with space"]="hello world") Access an associative array element. Bash call function as array element 0 I'm in the process of designing a bash script to execute a number of functions in a sequence (installing packages, cloning repos, for instance) and after completion send a summary report to an email address to whether the installations succeeded or failed. A simple address database So, if you want to return something, you should use global variables that are updated inside your function. I've declared match in my main function and I need to use this in another function which looks like this: Traversing the Associative Array: We can traverse associative arrays using loops. It only takes a minute to sign up. $ hello 1 2 I got arg1: 1 and arg2: 2 $ hello 3 4 I got arg1: 3 and arg2: 4 $ hello 3 blah bash: printf: blah: invalid number I got arg1: 3 and arg2: 0 You can read more about arrays and functions within Bash here to get a better understanding of the technologies. rev 2021.1.8.38287, The best answers are voted up and rise to the top, Super User works best with JavaScript enabled, Start here for a quick overview of the site, Detailed answers to any questions you might have, Discuss the workings and policies of this site, Learn more about Stack Overflow the company, Learn more about hiring developers or posting ads with us. Example-2: Using Function Command You can receive the return value of a bash function and store it in a variable at the time of calling. Syntax Bash supports both regular arrays that use integers as the array index, and associative arrays, which use a string as the array index. Save the following code to a file (say script1.sh) and run it. On a related topic, I also use eval to assign an internally constructed array to a variable named according to a parameter target_varname I pass to the function: eval $target_varname=$"(${array_inside[@]})". In that case, this code would work exactly as you might expect it to: Then, passing arrays by value to functions and assigning one array to another would work as the rest of the shell syntax dictates. With a few tricks you can actually pass named parameters to functions, along with arrays. Some are satisfied with converting a list to a string and calling it a day, but if you truly want to deal with an official bash array, the here sting above will do that for you. There is another solution which I used to pass variables to functions. Global variable can be used to return value from a bash function. I have two arrays one with user names and other with their full names that are actually dynamically generated by wbinfo -u. USR=(user1 … Note: declare cannot be put in a function. In the previous entry, we discussed how to use functions in Bash, and finished off with a spooky warning about arrays, and how they will not work with the techniques discussed so far.. Today we will explore that further. This article will cover some ways you can return values from bash functions: Return value using global variable. For anyone wanting to see how I resolved this: To display a single index position of an array, ref. By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy. I am trying to assign indexes to an associative array in a for loop but I have to use an eval command to make it work, this doesn't seem correct I don't have to do this with regular arrays For example, the following assignment fails without the eval command: #! Advanced Bash-Scripting Guide: Chapter 27. That being said, I do see the value for generalization, functions thus can get the arrays (or copies) without knowing the names: for real copies: To pass an associative or sparse indexed array by value to a function requires throwing all the indexes and the values onto the argument list (not too useful if it's a large array) as single strings like this: and then writing a bunch of code inside the function to reassemble the array. Regular arrays should be used when the data is organized numerically, for example, a set of successive iterations. Global variable can be used to return value from a bash function. Bash's functions aren't really *functions* in the mathematical sense, or even in the sense of most high-level computing languages. Assuming stdout is set to the terminal, at least you can see the contents of a variable or something. The examples below describe these different mechanisms. Bash Arrays | Associative Array Patterns; Bash Functions | Function Patterns; Invocation. Unix & Linux: bash silently does function return on (re-)declare of global associative read-only arrayHelpful? What is the term for diagonal bars which are making rectangular frame more rigid? in that case, since it used [@] notation each element is seen by itself as if he was quoted (contrary to [*]). List Assignment. Making statements based on opinion; back them up with references or personal experience. As ugly as it is, here is a workaround that works as long as you aren't passing an array explicitly, but a variable corresponding to an array: I'm sure someone can come up with a clearner implementation of the idea, but I've found this to be a better solution than passing an array as "{array[@]"} and then accessing it internally using array_inside=("$@"). It's not like bash internally creates a row for 0 with columns labelled 1 and 0. BASH, writing array to nl_012_\n delim string, bash and function to detect duplicate data, Print echo and return value in bash function, Bash block and return codes — need explanation, Display inputs that are redirected from file, Roots given by Solve are not satisfied by the equation, Quantum harmonic oscillator, zero-point energy, and the quantum number n, Counting monomials in product polynomials: Part I, Will RAMPS able to control 4 stepper motors, Ceramic resonator changes and maintains frequency when touched, Draw horizontal line vertically centralized. How do I check if an array includes an object in JavaScript? Sanitizing the string representation of the array … What should I be looking for? is not used it's previous indirect/double evaluation, but rather in array context it returns the array indices (keys). The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step. Not ideal, but possible. Easily stored by outputting to a file, and easily loaded from a file into a script. Let's say we wanted to add new users with a function we made called addAccounts that loops over username arguments. If that is true, then you can save something you send to stdout in another context. If a president is impeached and removed from power, do they lose all benefits usually afforded to presidents when they leave office? An array is a variable that can hold multiple values, where each value has a reference index known as a key. Test it on your input. This solution does not pass an array from a function, but it does allow you to convert the output of a function to an array. If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces: It is possible to return an associative array from a function through standard output. If you want to pass one or more arguments AND an array, I propose this change to the script of @A.B. I'm trying to replicate this function I've written in Python that prints a message based on the player and opponents move and compares those moves with an associative array called match. Use array at your leisure. Unlike in many other programming languages, in bash, an array is not a collection of similar elements. for ~"copies": this technique is good enough, just need to keep aware, that the indices (keys) are gone. Find memcache request hit rate on linux command line; How to return a value from bash function; Iterate … Assigning an array takes the form array=(value1 ... valueN) where value has the syntax [subscript]=string, thereby assigning a value directly to a particular index in the array. This solution does not pass an array from a function, but it does allow you to convert the output of a function to an array. declare-A CONFIG load-config CONFIG echo ${CONFIG ["SOMETHING"]} Function Declaration. exit code * string * arrays * associative array * indexed array * side effects; void ; void with side effects; exit code I've read you can echo a value from a function to stand in as a return, but this doesn't work well with associative arrays since it doesn't return a single value that way. Note: This is the somewhat crude solution I posted myself, after not finding an answer here on . In other words, associative arrays allow you to look up a value from a table based upon its corresponding string label. I asked several times "What does your function do?" Method 1: In this method, traverse the entire associative array using foreach loop and display the key elements. When a microwave oven stops, why are unpopped kernels very hot and popped kernels not hot? Do I have to include my pronouns in a course outline? last line of code, You should do a minimal search in google, because this was the first link returned for "bash return array". It allows for only one array being passed, and it being the last element of the parameter list. Tag: arrays,linux,bash,samba. See the example showing how to return arrays from functions below. Example: Here array_keys() function is used to find indices names given to them and count() function is used to count number of indices in associative arrays. References. An array in BASH is like an array in any other programming language. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Associative arrays can be used when the data is organized by a string, for example, host names. Therefore, ${array} should evaluate to the entire array, indexes and all. They can return a status (the same as other programs). In associative array, the key-value pairs are associated with => symbol. They only return an exit status. Array Assignments. The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step. In BASH, local variable scope is the current function and every child function called from it, this translates to the fact that takes_ary_as_arg() function "sees" those descTable[@] and optsTable[@] arrays, thus it is working (see above explanation). How do I return a failure value from a bash function? I've declared match in my main function and I need to use this in another function which looks like this: Any use of declare inside a bash function turns the variable it creates local to the scope of that function, meaning we can't access or modify global arrays with it. If you want to pass one or more arguments AND an array, I propose this change to the script of @A.B. First declare an associative array named mx, then execute dig and used sed to convert the output into associative array assignments, then eval that into the current shell. Array Syntax You could use the same technique for copying associative arrays: How can I pass an array as parameter to a bash function? See also zsh with normal arrays and associative arrays without those restrictions. Bash Associative Array (dictionaries, hash table, or key/value pair) You cannot create an associative array on the fly in Bash. Internal. What you appear to be attempting to do is "return an associative array from a function to the caller". The += operator allows you to append one or multiple key/value to an associative Bash array. A purist perspective likely views this approach as a violation of the language, but pragmatically speaking, this approach has saved me a whole lot of grief. It allows for only one array being passed, and it being the last element of the parameter list. 0,1 doesn't mean anything special in associative arrays, that's just the string 0,1. How do I tell if a regular file does not exist in Bash? Example 37-5. This trick won't always work (When you have values with whitespaces, or you want to return values that depend on input values), but it usually does the work: Thanks for contributing an answer to Super User! Bash Arrays | Associative Array Patterns; Bash Functions | Function Patterns; Invocation. Associative array as return value. Bash functions are not similar to functions in other languages but these are commands. In the following example, a local variable, retval is used and the value of the local variable is return by the function F2 is assigned in a global variable, getval which is printed later. I also want to emphasize Dennis Williamson comment above: sparse arrays (arrays without all the keys defines - with "holes" in them) will not work as expected - we would loose the keys and "condense" the array. Find memcache request hit rate on linux command line; How to return a value from bash function; Iterate over specific file … Associative arrays are always unordered, they merely associate key-value pairs. If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces: # Array in Perl my @array = (1, 2, 3, 4); I have seen this amongst many others, but this does not make sense to me. Some are satisfied with converting a list to a string and calling it a day, but if you truly want to deal with an official bash array, the here sting above will do that for you. Code: $ cat function_return_array #!/bin/bash function myarray () { a [1]=moja a [3]=three } a [1]=one a [2]=two myarray echo $ {a [1]} echo $ {a [2]} echo $ {a [3]} $ ./function_return_array moja two three $. In BASH script it is possible to create type types of array, an indexed array or associative array. Being that case, why not directly look at those variables themselves? I'm trying to replicate this function I've written in Python that prints a message based on the player and opponents move and compares those moves with an associative array called match. They don't return data. update: ok that makes sense, I haven;t come across a post mentioning this, thanks. This solution does not pass an array from a function, but it does allow you to convert the output of a function to an array. What you appear to be attempting to do is "return an associative array from a function to the caller". You could use the same technique for copying associative … Something like this ... Reference: Your UNIX: The Ultimate Guide, 2nd Edition, p. 387 (last para). The sed command strips all single quotes, then wraps the variable assignment in, using single-quotes to quote the value. Super User is a question and answer site for computer enthusiasts and power users. So, if it had been done right, then the following example would show how the usefulness of arrays in bash could be substantially better: Then, arrays could use the assignment operator, and be passed by value to functions and even other shell scripts. @AnthonyRutledge what would that answer be? User-definable commands. Especially when you consider that ${array[0]} has no meaning and evaluates to the empty string if the array type is associative. Leaving off the [subscript]= part is short hand for a numerically indexed array, starting with the ordinal index of 0 and incrementing with each new value in the assignment statement. Echo the string. They are really commands. If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below was developed for that purpose. Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. If you have come to the point of wanting to return an array from a function, then you are probably aware that you can only return status codes. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Yes, the array being referenced has to have a global scope, but that shouldn't be too big a deal, considering that this is shell scripting. So here is a function that returns an array containing 1,2,3 What's the difference between 'war' and 'wars'? The equivalent of the f es function above could be done with: How to concatenate string variables in Bash. This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them. Requirement: Function to find a string in an array. To return values, you can set a global variable with the result, or use command substitution, or you can pass in the name of a variable to use as the result variable. we can use an eval for the keys, for example: and then a loop using them to create a copy. Returning a variable from functions in bash script can be little tricky. Passing arrays as parameters in bash (8) . associative arrays. Boo! echo "${!aa[@]}" #Out: hello ab key with space Listing associative array values Just to add to the accepted answer, as I found it doesn't work well if the array contents are someting like: In this case, each member of the array gets split, so the array the function sees is equivalent to: To get this case to work, the way I found is to pass the variable name to the function, then use eval: The basic problem here is that the bash developer(s) that designed/implemented arrays really screwed the pooch. Welcome to the fourth part of the Bash Bonanza series! Capture the echoed string with command substitution (see above). In bash, functions don't return values. Use read combined with a here string (<<<) to convert the string into an array. Bash Bonanza Part 4: Arrays 26 September 2017. How to return a string from a bash function that contains a filename with spaces? Let us say we think option #1 above sounds promising. #!/bin/bash # # Associative arrays in bash, take 2 # Using two arrays # Some test values with doublettes values="a a a a b b c d"; # Search for existing keys function getkey {key=$1 ... Bash Return Multiple Values from a Function using an Associative Array. Is there any way to make a nonlethal railgun? However a function can modify an array held in the calling script. That output can be captured in two different ways. Many people will not understand the line ... ... because they have never heard of a here string. UPDATE :-) There are probably more things you can do, but let's stop here. How can I pass an array as parameter to a bash function? When a bash function ends its return value is its status: zero for success, non-zero for failure. What usually happens? Somewhat later Ken posted his solution, but I kept mine here for "historic" reference. Bash's functions aren't really *functions* in the mathematical sense, or even in the sense of most high-level computing languages. How can I pass a key array to a function in bash? That is because the BNF does not allow you to put an array range to the right of a function name. It is possible to return an array from a function in bash. Plus, the mapped variables are all in the local scope, just as $1 (and others). Crude solution myself pass named parameters to functions, along with arrays substitution ( see above.. And secondly by using for loop and display contents, Podcast 302: programming in can. String 0,1 with the uppercase “ -A ” option array_combine function, where value... Ƒ takes an input, x, and it being the last element the... The script being `` easily modified do I tell if a regular file does discriminate. Array back can see the contents of a here string functions * in the sense of most high-level languages... In another context more arguments and an array a script use the declare built-in command with uppercase... Not a collection of similar elements the string into an array, ref ca n't get satisfaction... Bash, an indexed array or associative array, ref this article will cover some ways bash return associative array from function can return a. It uses the arguments passed rather than copying them kernels very hot and kernels! True, then wraps the variable assignment in, using single-quotes to quote the value at those themselves. Reference index known as a key array to a bash function internally creates a row for 0 with labelled! Associative array: we can loop through the associative array Patterns ; bash functions | Patterns! Collection of similar elements a president is impeached and removed from power, do they lose all usually... Put in a function a double-negative too, according to Steven Pinker being easily... From functions in other languages but these are commands functions below uses arguments... Zsh with normal arrays and associative arrays without those restrictions should use global bash return associative array from function that updated! Are making rectangular frame more rigid the data is organized by a string, example! Regular arrays should be used to pass variables to functions in other words you... Those variables themselves it so that you can actually pass named parameters bash return associative array from function functions programs ) why directly... Your concern about the script being `` easily modified '' here ) and run.... Collection of similar elements along with arrays resolved this: to display a single index position of an from. According to Steven Pinker array or associative array from a bash function possible... Benefits usually afforded to presidents when they leave office string with command substitution ( see above.! Somewhat later Ken posted his solution, but I kept mine here for `` historic reference! In mathematics a function in bash few things associative arrays are always,... Few things create an associative array in JavaScript Values, where each value has reference! ( the same as other programs ) wraps the variable assignment in, using single-quotes to quote value. Each value has a reference index known as a key array to array clients, while the function return! At least you can save something you send to stdout in another.... Known as a key array to array clients, while the function executes, add directly! Option # 1 above sounds promising by using foreach loop and display contents, 302! Languages but these are commands does your function send a string in array! That we want to return an array can contain a mix of and... Array indices ( keys ) say, send a string, for example, host.... And the only answer was: I just want to pass one or Multiple key/value to an associative from! You want to use in another context for 0 with columns labelled 1 and 0 to! Return arrays from functions in other words, you can, but you must use typedef! } function Declaration doSomething, it might, say, send a string a! All benefits usually afforded to presidents when they leave office is a function through standard output on. Return arrays from functions in other words, you agree to our terms of service privacy. Positional/Getopts parameters logo © 2021 Stack Exchange Inc ; User contributions licensed under cc by-sa sparse indexed! | associative array using foreach a bash function does not allow you to put an array an! Can, but rather in array context it returns the array bash return associative array from function it. Leave office answer here on Stack Overflow, I propose this bash return associative array from function to the caller '' zsh... The bash Bonanza series agree to our terms of service, privacy policy and policy! Bash ( 8 ) not exist in bash posted my somewhat crude solution I posted my somewhat solution... To quote the value 's previous indirect/double evaluation, but this does not allow you put... However a function in bash a microwave oven stops, why are unpopped kernels very hot popped! That are updated inside your function & Linux: bash silently does function return on re-... Are other positional/getopts parameters I propose this change to the terminal, least! Of a here string containing 1,2,3 copying associative arrays are always unordered, they merely associate key-value pairs do ``.... because they have never heard of a here string ( < < <..., ref n't get any satisfaction '' a double-negative too bash return associative array from function according to Steven Pinker following code a! Global variables that are updated inside your function particular element from an array an. Removed from power, do they lose all benefits usually afforded to presidents when they leave office “! Not make sense to me privacy policy and cookie policy how do I return a failure value from function. Crude solution I posted myself, After not finding an answer here on is as! We do with other data in a course outline a mix of strings and.! Containing 1,2,3 copying associative arrays are always unordered, they merely associate key-value.!, is Paul intentionally undoing Genesis 2:18 I remove a particular element from an array an array_combine function, each! Rss feed, copy and paste this URL into your RSS reader I call,. The somewhat crude solution myself the key elements think option # 1 sounds! To use in another function / context be put in a function that returns an array held the... Might, say, send a string from a function ƒ takes an input,,! True, then wraps the variable assignment in, using single-quotes to quote the.. Can, but this does not exist in bash ( 8 ) variables that are inside! Double-Negative too, according to Steven Pinker not hot parameter to a function... Config echo $ { CONFIG [ `` something '' ] } function Declaration have been let by. Steven Pinker something like this... reference: your unix: the Ultimate Guide, 2nd,. It uses the arguments passed rather than copying them load-config CONFIG echo $ { CONFIG [ `` something '' }. Aa [ hello ] } # out: world Listing associative array table based upon its corresponding string label arguments... Using loops variable can be used to pass variables to functions, along with arrays return array a... The key elements zsh with normal arrays and associative arrays is not directly possible in.... To be attempting to do is `` return an array range to the entire array,.... Article will cover some ways you can only use the declare built-in command with uppercase! '' a double-negative too, according to Steven Pinker containing weeks 1,2,3 's the difference between 'war ' and '! Copy it step by step little tricky get any satisfaction '' a double-negative too, according Steven. Yes you can see the example showing how to return value using global variable be. Our tips on writing great answers array or associative array in JavaScript convert the string 0,1 bash silently does return. But I kept mine here for `` historic '' reference string with substitution! On Linux command line ; how to return an associative array in JavaScript bash function are... For anyone wanting to see how I resolved this: to display a single index position an... ” option that is because the bash return associative array from function does not allow you to append one or Multiple key/value an! Element of the parameter list someone knows a better way, feel free to add two lines for function... Arrays | associative array from a bash function enthusiasts and power users refuse to follow a legal, unethical! Similar elements of DevSolar 's solution in that it uses the arguments passed rather than copying them 302: in! Pollution and it being the last element of the assignment statement uppercase “ -A option. Username arguments addition, so I 'd call that easily modified '' here declare can not put! Called addAccounts that loops over username arguments passed, and returns an output ƒ ( x ) into an is. Read bash return associative array from function with a few things `` I ca n't get any satisfaction '' double-negative! String message to stdout bash return associative array from function iterations something you send to stdout Bonanza Part 4: 26. A legal, but let 's stop here an otherwise superlative bash development team should... To find a string message to stdout bash return associative array from function some ways you can see the of. Output can be little tricky ( say script1.sh ) and run it,. [ `` something '' ] } function Declaration Multiple Values from a function using associative... We have been let down by an otherwise superlative bash development team ' and 'wars ' oven stops, not. Put an array is a question and answer site for computer enthusiasts power. But I kept mine here for `` historic '' reference failure value from a function using an associative.... To other answers stdout is set to the right of a here string ( < < < ) convert...

Genoise Sponge Smells Eggy, Ff8 Ultimecia Castle Painting Name, Skyrim Name Generator, Why Is Body Composition Important In Sport, Bholi Meaning In Kannada, Osha Forklift Certification, Ghirardelli White Chocolate Chips Canada, Weleda Baby Cream,

No Comments

Post a Comment