Sunday, 4 December 2011

bash arrays


Associative array: declare -A variable: The variable is an associative array of strings (bash 4.0 or higher).
Read Only: declare -r variable: The variable can no longer be modified or unset.
Export: declare -x variable: The variable is marked for export which means it will be inherited by any subshell or child process.
${arr[0]} = refers to first element of array.
${#host[*]} = no. of elements in a array.
${arr[*]} = refers to all elements of array.
${#arrayname[n]} should give the length of the nth element in an array.
${arr[@]:3:2} = return the all elements of the array starting from 4th element (3 index) to 6th element (2 elements). First number is the position from which to extract and the next number is the number of elemets from that position to extract.
${arr[2]:0:4} = extracts first 4 characters of 3rd element of the array. For example if the arr[2]=ubuntu, then the above will print ubun
Search and replace a array element:
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]/Ubuntu/SCO Unix}")

Add an element to an existing Bash Array:
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]}" "AIX" "HP-UX")
echo ${Unix[7]}
This can also be doen via
Unix+=("AIX" "HP-UX")

Remove an Element from an Array
unset Unix[3]
The above will assign null value at position 3. To completely remove 3 positon valu. reassign the araray removing positon 3 vlaue like this.
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})

Remove Bash Array Elements using Patterns
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
patter=( ${Unix[@]/Red*/} )
echo ${patter[@]}

Deleting an Entire Array:
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
unset Unix

Load Content of a File into an Array:
mapfile -t filecontent < "$logfile"
printf "%s\n" "${filecontent[@]}"
you cannot use echo since it will convert new line into single space.

No comments:

Post a Comment