bash - Parameter as reference? -
i trying make function swap() this
swap(){ #swap $1 , $2 here }
what want swap array let have
array[0]=12 array[1]=45 array[2]=99 swap $array[0] $array[1]
so want swap array[0] becomes 45 , array[1] becomes 12 after swap function. thinking of doing swapping referencing $array[0] (such pointer in c) , $array[1] changed. found command eval , upvar seriously, don't understand thing. pretty new shell scripting , of documentation out there confused me lot.
bash
arrays little tricky. clearest thing can write function take three arguments, array name , 2 indices swap. requires treat array
global variable; cannot pass entire array single object in bash
.
(this require bash
4 or later, introduced -g
flag declare
.)
swap () { local name=$1 local a=$2 local b=$3 local aname=$name[$a] local bname=$name[$b] local tmp=${!aname} # e.g. tmp=${array[$a]} declare -g "${aname}=${!bname}" # e.g. array[$a]=${array[$b]} declare -g "${bname}=$tmp" # e.g. array[$b]=$tmp }
bash
4.3 introduces namerefs (declare -n)
simplify letting declare local array acts alias global array.
swap () { declare -n arr=$1 local a=$2 b=$3 local tmp=${arr[$a]} arr[$a]=${arr[$b]} arr[$b]=$tmp
}