Christopher Barry on 29 May 2016 18:22:25 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Bash question


On Sun, 29 May 2016 17:26:58 +0000 (UTC)
Gregory Deal <1deal@comcast.net> wrote:

>Even after checking the "learning bash" book and searching, I'm having
>a little trouble explaining some bash functioning. I'm trying to
>process some command output, making an array of its output lines. I
>was trying to check for the "no output" case (which goes right back to
>a prompt) by interrogating the final array length. But even with no
>command output, I get a length of 1. Could someone explain this?
>Thanks. 
>
>Script: 
>
>#!/bin/bash 
>
># DTD specifies 0 or 1 <rules>, so check if any before processing. 
>echo "Rules content:" 
>xmlpathval.py ~/program1/sample2.xml "/sync/rules[1]/text()" | 
>while IFS= read -r line; do 
>echo "-->'$line'" 
>done 
>echo "IFS='$IFS'" 
>
>rulesInfo=$(xmlpathval.py ~/program1/sample2.xml
>"/sync/rules[1]/text()") <<<<<<< raw output shown below if [[ -z
>$rulesInfo ]]; then echo "No rules found." 
>fi 
>echo "rulesInfo='$rulesInfo'" 
>
>IFS= 
>unset rulesArray 
>readarray -t rulesArray <<< "$rulesInfo" 
>echo "length=${#rulesArray[@]}" 
>if [[ ${#rulesArray[@]} -eq 0 ]]; then 
>echo "empty" 
>else 
>echo "not empty" 
>fi 
>echo "rulesArray(single echo)=${rulesArray[@]}" 
>echo rulesArray from loop= 
>for element in "${rulesArray[@]}" 
>do 
>echo "'$element'" 
>done 
>
>Input: 
>
>gkd@sisko:~/program1$ xmlpathval.py sample2.xml
>"/sync/rules[1]/text()" gkd@sisko:~/program1$ echo $? 
>0 
>
>Results : 
>
>gkd@sisko:~/scripts$ ./test.sh 
>Rules content: 
>IFS=' 
>' 
>No rules found. 
>rulesInfo='' 
>length=1 
>not empty 
>rulesArray(single echo)= 
>rulesArray from loop= 
>'' 
>gkd@sisko:~/scripts$ 
>
>

t=( '' )
echo ${#t[@]}
1

yet,

[[ ${t[@]} ]] && echo yes
<no output>

therefore,

test for an actual value in ${rulesArray[@]} as well

(( ${#rulesArray[0]} )) && [[ "${rulesArray[@]}" ]] && do stuff


-- 
Regards,
Christopher
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug