BLU Discuss list archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
passing arrays and working with arrays in BASH
- Subject: passing arrays and working with arrays in BASH
- From: tbs-Gb/NUjX2UK8 at public.gmane.org (theBlueSage)
- Date: Fri, 26 Mar 2010 17:12:33 -0400
Ho Folks, so it has taken me _ages_ to get this to work and Icant believe this is the best/only way to get this done : Problem : I am writing server install scripts, and BASH is the chosen tool. I needed to write a function that could receive an array and a value, and then simply return the position in the array if the given value. This is seriously easy in something like PHP using in_array($arr, $val), but in was a completely different kettle of fish in BASH. Solution (that I have working right now, in example form): ------------ start code snippet -------------- #!/bin/bash function search_array() { index=0 array=( "$@" ) #echo ${array[@]} let TCNT=${#array[@]}-1 LASTVAL=${array[${#array[@]}-1]} while [ "$index" -lt "$TCNT" ]; do if [ "${array[$index]}" = "$LASTVAL" ]; then echo $index return fi let "index++" done echo "" } echo -e -n "enter a value to search for : " read -e KEY arr=( f q e c d s a ) arr[${#arr[@]}+1]=$KEY position=$(search_array "${arr[@]}") if [ -z "$position" ]; then echo -e "the value "$KEY" is not in the array" else echo -e "the value "$KEY" was found at position: "$position fi exit 0 -------- end code snippet ---------------- where : 'KEY' is the value to search for and 'arr' is the array to search in I did it this way as I couldn't find any other way to pass an array _and_ a scalar value to the function. The result is I add the scalar to the end of the array, pass it to the function and then peel it off again. SURELY there is a better way of doing it than this ? thanks for any suggestions Richard -- theBlueSage <tbs-Gb/NUjX2UK8 at public.gmane.org>
- Follow-Ups:
- passing arrays and working with arrays in BASH
- From: tmetro-blu-5a1Jt6qxUNc at public.gmane.org (Tom Metro)
- passing arrays and working with arrays in BASH
- Prev by Date: Linux on netbooks
- Next by Date: passing arrays and working with arrays in BASH
- Previous by thread: "snapshot" RAID
- Next by thread: passing arrays and working with arrays in BASH
- Index(es):