0

I have this structure in Shell Script BASH

i=0
while read linha_reg
do
    REG_ADDRESS=$(echo $linha_reg | cut -f1 -d ' ')
    [ $REG_ADDRESS -lt 16] && T[$i]=$REG_ADDRESS || S[$i]=$REG_ADDRESS
    i=$((i+1))
done < register.txt

while read linha_inst
do
    RS=$(echo $linha_inst | cut -f4 -d ' ')
    RS=$(echo $RS | cut -f1 -d ',')

    RS_INDEX=${RS:2:2}
    RS_LETTER=${RS:1:1}

    [ "$RS_LETTER" == "s" ] && echo ${S[$RS_INDEX]} 
done < instruction.txt

With this snippet I have only a blank space in the echo ${S[$RS_INDEX]} when I execute it on Terminal. However, if I write

echo ${S[@]}

It outputs the entire array, as requested by the echo. If I write

echo ${S[3]}

Doesn't work also.

I'm lost because I don't know what explains this and I want it to return only a single element, as the big snippet does but it doesn't output by unknown reasons.

Cheers

14
  • 2
    Also, you increment $i whether you assign to T or S; that will leave gaps in the array you don't assign to. Commented Aug 27, 2014 at 18:52
  • 2
    Check how many elements you have in S with echo ${#S[@]} to verify you have more than 1 element. Then you know how many to expect. You may also want to post example lines of register.txt and instruction.txt. Using echo | cut ... is a wonky way to do what should be done by substring extraction. Commented Aug 27, 2014 at 19:07
  • 1
    oh -- your indexes are not 0-7! You need 2 different counters for T[x] and S[y] in order to keep you indexes straight. use i for S and say j for T. Commented Aug 27, 2014 at 19:21
  • 1
    To keep the indexes straight, so something like i=0; j=0; .. [ $REG_ADDRESS -lt 16] && { T[$i]=$REG_ADDRESS; ((i++)); } || { S[$j]=$REG_ADDRESS; ((j++)); } --or-- declare -a T; declare -a S and then use T+=$REG_ADDRESS and S+=$REG_ADDRESS Commented Aug 27, 2014 at 19:29
  • 1
    @DavidC.Rankin T+=($REG_ADDRESS), otherwise you simply perform string concatenation on ${T[0]}. Commented Aug 27, 2014 at 19:39

1 Answer 1

1

To add to an array, use var+=(value) like @chepner suggested. Using var[$i]=value results in sparse arrays, where some indexes are undefined.

Also:

  • Use More Quotes™!
  • In Bash you can use here strings like some_command <<< "$variable" to avoid echo.
  • When you do a && b || c, c is run if either a or b fails. To avoid this, use the standard

    if a
    then
        b
    else
        c
    fi
    
  • Use a single = with [ (see help test).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.