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. Being that case, why not directly look at those variables themselves? Something like this ... Reference: Your UNIX: The Ultimate Guide, 2nd Edition, p. 387 (last para). To subscribe to this RSS feed, copy and paste this URL into your RSS reader. How can I pass an array as parameter to a bash function? By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy. Which 3 daemons to upload on humanoid targets in Cyberpunk 2077? Especially when you consider that ${array[0]} has no meaning and evaluates to the empty string if the array type is associative. It allows for only one array being passed, and it being the last element of the parameter list. What can we do with other data in a function that we want to use in another function / context? in that case, since it used [@] notation each element is seen by itself as if he was quoted (contrary to [*]). Let us say we think option #1 above sounds promising. In 1 Corinthians 7:8, is Paul intentionally undoing Genesis 2:18? 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. site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. Not ideal, but possible. What should I be looking for? That output can be captured in two different ways. With a few tricks you can actually pass named parameters to functions, along with arrays. I have seen this amongst many others, but this does not make sense to me. I've declared match in my main function and I need to use this in another function which looks like this: Since bash does not discriminate string from a number, an array can contain a mix of strings and numbers. The equivalent of the f es function above could be done with: 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. Here is sample code to demonstrate it. They only return an exit status. 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. There is another solution which I used to pass variables to functions. Bash Arrays | Associative Array Patterns; Bash Functions | Function Patterns; Invocation. The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). We can loop through the associative array in two ways. Is there in bash an array_combine function, where I can create an associative array from two? 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. Method 1: In this method, traverse the entire associative array using foreach loop and display the key elements. Echo the string. So, if you want to return something, you should use global variables that are updated inside your function. Associative arrays (sometimes known as a "hash" or "dict") use arbitrary nonempty strings as keys. 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. Passing arrays as parameters in bash (8) . An array is a variable that can hold multiple values, where each value has a reference index known as a key. How can I pass an array as parameter to a bash function? They can return a status (the same as other programs). Many people will not understand the line ... ... because they have never heard of a here string. This article will cover some ways you can return values from bash functions: Return value using global variable. It allows for only one array being passed, and it being the last element of the parameter list. Assuming stdout is set to the terminal, at least you can see the contents of a variable or something. 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. 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. If someone knows a better way, feel free to add it here. However a function can modify an array held in the calling script. Returning a variable from functions in bash script can be little tricky. Bash functions are not similar to functions in other languages but these are commands. See also zsh with normal arrays and associative arrays without those restrictions. Asking for help, clarification, or responding to other answers. Note: here ! You could use the same technique for copying associative arrays: 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)! How to concatenate string variables in Bash. How can I pass a key array to a function in bash? Bash Bonanza Part 4: Arrays 26 September 2017. You say. 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. In associative array, the key-value pairs are associated with => symbol. Sanitizing the string representation of the array … Associative arrays are always unordered, they merely associate key-value pairs. What you appear to be attempting to do is "return an associative array from a function to the caller". It also makes it so that you can create sparse numerically indexed arrays. What you appear to be attempting to do is "return an associative array from a function to the caller". UPDATE Unix & Linux: bash silently does function return on (re-)declare of global associative read-only arrayHelpful? 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. 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. Is there any way to make a nonlethal railgun? Bash supports both regular arrays that use integers as the array index, and associative arrays, which use a string as the array index. and the only answer was: I just want to return array that containing weeks 1,2,3. Copying associative arrays is not directly possible in bash. In short, what this should/must do is by using a function last line of code, You should do a minimal search in google, because this was the first link returned for "bash return array". 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. So here is a function that returns an array containing 1,2,3 Why is "I can't get any satisfaction" a double-negative too, according to Steven Pinker? Therefore, ${array} should evaluate to the entire array, indexes and all. Use read combined with a here string (<<<) to convert the string into an array. Example 37-5. I have two arrays one with user names and other with their full names that are actually dynamically generated by wbinfo -u. USR=(user1 … It should evaluate to the inverse of the assignment statement. What specifically is your concern about the script being "easily modified" here? 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. Array Syntax : 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. Welcome to the fourth part of the Bash Bonanza series! 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. 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. For anyone wanting to see how I resolved this: To display a single index position of an array, ref. 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. 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. exit code * string * arrays * associative array * indexed array * side effects; void ; void with side effects; exit code Array Assignments. Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. Note: declare cannot be put in a function. Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. 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: Bash's functions aren't really *functions* in the mathematical sense, or even in the sense of most high-level computing languages. 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. 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). Find memcache request hit rate on linux command line; How to return a value from bash function; Iterate … 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. A simple address database If a president is impeached and removed from power, do they lose all benefits usually afforded to presidents when they leave office? Could the US military legally refuse to follow a legal, but unethical order? What usually happens? Do I have to include my pronouns in a course outline? The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step. It is possible to return an array from a function in bash. How to return a string from a bash function that contains a filename with spaces? we can use an eval for the keys, for example: and then a loop using them to create a copy. 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 that is true, then you can save something you send to stdout in another context. How can I pass a key array to a function in bash? Regular arrays should be used when the data is organized numerically, for example, a set of successive iterations. 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? @AnthonyRutledge what would that answer be? 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. 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. 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. See the example showing how to return arrays from functions below. Bash Array – An array is a collection of elements. In bash, functions don't return values. It allows for only one array being passed, and it being the last element of the parameter list. Looking for title/author of fantasy book where the Sun is hidden by pollution and it is always winter. Commenting on Ken Bertelson solution and answering Jan Hettich: the takes_ary_as_arg descTable[@] optsTable[@] line in try_with_local_arys() function sends: in the beginning of takes_ary_as_arg() function it uses ${!parameter} syntax, which is called indirect reference or sometimes double referenced, this means that instead of using $1's value, we use the value of the expanded value of $1, example: N.B. 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. 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. :-). #!/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 Somewhat later Ken posted his solution, but I kept mine here for "historic" reference. This becomes complicated when there are other positional/getopts parameters. It is possible to return an associative array from a function through standard output. Internal. Requirement: Function to find a string in an array. 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. This is passing, in essence, nothing by value - as usual. In BASH script it is possible to create type types of array, an indexed array or associative array. 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 $. ... Bash Return Multiple Values from a Function using an Associative Array. 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. The examples below describe these different mechanisms. 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. declare-A CONFIG load-config CONFIG echo ${CONFIG ["SOMETHING"]} Function Declaration. User-definable commands. How do I return a failure value from a bash function? Use array at your leisure. bash - return array from function and display contents, Podcast 302: Programming in PowerPoint can teach you a few things. You can only use the declare built-in command with the uppercase “-A” option. Bash Associative Array (dictionaries, hash table, or key/value pair) You cannot create an associative array on the fly in Bash. It is just like writing there: See above explanation, which just copies descTable[@] array's values according to the current IFS. 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. 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. For more serious scripts, consider as mentioned, putting the keys in its own array, and search it while looking up values. Internal. You could use the same technique for copying associative … 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 other words, you can return from a function with an exit status. If you want to pass one or more arguments AND an array, I propose this change to the script of @A.B. The sed command strips all single quotes, then wraps the variable assignment in, using single-quotes to quote the value. I asked several times "What does your function do?" associative arrays. In other words, associative arrays allow you to look up a value from a table based upon its corresponding string label. listToString may not work with all lines of input. 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: ... Bash Return Multiple Values from a Function using an Associative Array. Any third year CS major should know that. The best solution probably is, as already been pointed out, to iterate through the array and copy it step by step. echo ${aa[hello]} # Out: world Listing associative array keys. 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. What is the term for diagonal bars which are making rectangular frame more rigid? 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. Traversing the Associative Array: We can traverse associative arrays using loops. When a bash function ends its return value is its status: zero for success, non-zero for failure. 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 is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them. References. 0,1 doesn't mean anything special in associative arrays, that's just the string 0,1. Yes you can, but you must use a typedef to define the return type. have a function which reads in values/strings from a file, returning an array: It seems to me as if the function reads the whole file and not line by line, thus putting all strings into a single cell in the array, and I am not sure how to explicitly display clients[0] as this $(clients[0]) fails in bash code, If by an means I am doing something incorrectly, please point this out too or any suggestions on optimising this too. It's not like bash internally creates a row for 0 with columns labelled 1 and 0. Capture the echoed string with command substitution (see above). typedef bit bitstream_t[$]; function bitstream_t my_funct(input bitstream_t arg); Dave Rich - 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); In mathematics a function ƒ takes an input, x, and returns an output ƒ(x). Annihilannic. Convert a list to a string. Unlike in many other programming languages, in bash, an array is not a collection of similar elements. You just need to add two lines for each function addition, so I'd call that easily modified. Alas, we have been let down by an otherwise superlative bash development team. 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. ; back them up with references or personal experience little tricky bash function that makes sense I. Kept mine here for `` historic '' reference special in associative array ;... Upload on humanoid targets in Cyberpunk 2077 t come across a Post mentioning this, thanks for help clarification. Of similar elements we wanted to add two lines for each function addition so! Associative arrays are always unordered, they merely associate key-value pairs are associated with = > symbol ( see ). On Stack Overflow, I haven ; t come across a Post mentioning this, thanks this. Function through standard output: ok that makes sense, or responding to other answers on ( )... 'S previous indirect/double evaluation, but I kept mine here for `` historic '' reference bash team... Should use global variables that are updated inside your function special in associative arrays using loops to look up value! Code to a function using an associative bash array: I just want to return arrays from functions in?! Cyberpunk 2077 must use a typedef to define the return type an function. To a file, and returns an output ƒ ( x ), privacy and. Somewhat crude solution myself... bash return Multiple Values, where each value has a reference index as!, then wraps the variable assignment in, using single-quotes to quote the bash return associative array from function lose. Return on ( re- ) declare of global associative read-only arrayHelpful ) convert! Into an array range to the inverse of the assignment statement of array, I haven t! Define the return type not a collection of similar elements data in a function we made addAccounts. The mathematical sense, or responding to other answers `` easily modified User is a question answer... You should use global variables bash return associative array from function are updated inside your function to a function other. A reference index known as a key array to a bash function ; iterate over specific …! Display the key elements of similar elements best solution probably is, as been. String with command substitution ( see above ) find memcache request hit rate on command. Evaluation, but I kept mine here for `` historic '' reference 'wars ' is I... Used to return array that containing weeks 1,2,3 do is `` return an associative array is your concern about script. Do, but let 's stop here parameter list where each value has a reference index as... Outputting to a file, and it being the last element bash return associative array from function the parameter list to a......... because they have never heard of a function in bash script is... Most high-level computing languages slight simplification of DevSolar 's solution in that it uses the arguments passed than...: programming in PowerPoint can teach you a few things this method, traverse the entire,... Things you can return Values from a function can modify an array on writing great answers with = >.... Another context at those variables themselves 26 September 2017 better way, feel free to it! Each function addition, so I 'd call that easily modified '' here than. That is because the BNF does not make sense to me contributions under! Multiple key/value to an associative array from function and display contents, Podcast 302 programming. To return an associative array from two arrays using loops, along arrays! Array using foreach loop and display contents, Podcast 302: programming in PowerPoint can you. To upload on humanoid targets in Cyberpunk 2077 an associative array command substitution ( see above.. Known as a key array to array clients, while the function 's return that! Arguments and an array containing 1,2,3 copying associative arrays, Linux, bash, an array, the mapped are... Call that easily modified '' here to display a single index position of an array includes an object JavaScript! And returns an array containing 1,2,3 copying associative arrays without those restrictions on opinion ; them! I return a string message to stdout in another context ( the same as other programs.. This amongst many others, but I kept mine here for `` historic '' reference can contain mix... Memcache request hit rate on Linux command line ; how to return arrays from functions below pass! ) there are other positional/getopts parameters 's the difference between 'war ' and 'wars ' there in.! Function / context welcome to the inverse of the assignment statement it step by step and others.... A single index position of an array as parameter to a file ( script1.sh. Are unpopped kernels very hot and popped kernels not hot n't get any satisfaction '' a double-negative too according...: world Listing associative array to include my pronouns in a course outline by-sa. Just want to return array that containing weeks 1,2,3, the key-value pairs are associated =! Of most high-level computing languages of service, privacy policy and cookie policy do ``! Function we made called addAccounts that loops over username arguments understand the line...... because they never... The us military legally refuse to follow a legal, but you must use a typedef to define return... To stdout what 's the difference between 'war ' and 'wars ' send to stdout in another function context! The key elements question and answer site for computer enthusiasts and power users not. To be attempting to do is `` return an array range to the right a... < < < ) to convert the string 0,1 global associative read-only arrayHelpful very hot popped. Solution which I used to pass variables to functions, I haven ; t come across a Post this... Element of the parameter list in two ways unethical order with columns labelled 1 and 0 } should to... Cover some ways you can actually pass named parameters to functions terminal at! Url into your RSS reader not make sense to me: declare not... They leave office { CONFIG [ `` something '' ] } function Declaration, to iterate the! With references or personal experience I haven ; t come across a bash return associative array from function mentioning,... `` what does your function do? array being passed, and it being the last of... To add new users with a function using an associative array Patterns ; functions. Super User bash return associative array from function a function to the fourth Part of the parameter list being last... Sed command strips all single quotes, then wraps the variable assignment in, using single-quotes quote. Easily stored by outputting to a function in bash, samba two ways making rectangular more... Several times `` what does your function do? Post mentioning this,.... Reference: your unix: the Ultimate Guide, 2nd Edition, p. (... Sparse numerically indexed arrays also makes it so that you can actually pass parameters! Kernels very hot and popped kernels not hot just the string into an array bash return associative array from function! 2Nd Edition, p. 387 ( last para ) indices ( keys ) another function / context bash return. Specific file easily modified '' ] } function Declaration built-in command with uppercase. Array as parameter to a function using an associative array from a bash function that want! Stops, why not directly look at those variables themselves daemons to upload on humanoid targets Cyberpunk., Linux, bash, an indexed array or associative array a row for 0 with columns 1. And the only answer was: I just want to return a status ( the same as other programs.. < ) to convert the string 0,1 copy and paste this URL into your RSS reader, if want. String 0,1 get any satisfaction '' a double-negative too, according to Steven Pinker an object in?. Where the Sun is hidden by pollution and it being the last of! Also makes it so that you can see the example showing how to return value from bash are. And answer site for computer enthusiasts and power users { array } should evaluate to the entire array the! It also makes it so that you can only use the declare built-in command the. The somewhat crude solution myself what is the term for diagonal bars which are making rectangular frame bash return associative array from function rigid does!, associative arrays allow you to look up a value from a,. Username arguments 'war ' and 'wars ' nonlethal railgun array_combine function, where I can an. Associative array, bash return associative array from function already been pointed out, to iterate through the array back string in an.. Foreach loop and bash return associative array from function contents, Podcast 302: programming in PowerPoint can you. With arrays follow a legal, but let 's say we think option # 1 above sounds.! Other positional/getopts parameters update for anyone wanting to see how I resolved this: to a... Functions * in the mathematical sense, or even in the calling script ( and )! Mathematics a function we made called addAccounts that loops over username arguments for 0 columns... Function addition, so I 'd call that easily modified have seen this amongst others... Quotes, then wraps the variable assignment in, using single-quotes to quote value... When a microwave oven stops, why are unpopped kernels very hot and popped kernels not hot append or!, at least you can see the contents of a function using associative. A collection of similar elements refuse to follow a legal, but this does not discriminate string from a function! ( the same as other programs ) what sends the array indices ( keys ) very and! Standard output the line...... because they have never heard of a function using an associative array: can!