0

I was trying to write a bash script to run several cases where the steps are the following:

  1. reading a .txt file in an array
  2. concatenate each element of an array with a specific string
  3. opening several screens in detached mode and then changing a specific file (in this case seq.txt) and run a few commands

The code is as follows:

COUNTER=0
readarray t1Gad < t1_gad.txt
while [  $COUNTER -lt 5 ]; do
    NUM_DEVICE=8
    DEVICE_NO=`expr $COUNTER % $NUM_DEVICE`
    string1='objGa_'
    string2=${t1Gad[$COUNTER]}
    #string2='hello'
    string=$string1$string2
    echo $string2
    echo $string1
    echo $string
    screen -d -m -S "$COUNTER" bash -c 'cd $HOME/Downloads && sed -i '2s/.*/$string/' seq.txt && cat seq.txt; exec sh'
    let COUNTER=COUNTER+1
done

The funny thing is that if I replace string2 with a fixed string, it is working fine, but it is not working with array elements of the array.

I would be happy if someone explains it to me. I am very new to bash scripting but desperately want to learn this very useful but ugly scripting language.

I found the problem but I do not know how to solve it. While doing the string concatenation, say e.g.

    string1="objGa_"
string="$string1${t1Gad[$COUNTER]}"

(say 192 is that specific element)and in that case it is substituting

objGa_192 ' ' 

inside the screen. I do not know how to get rid of that space and where it is coming from.

t1_gad.txt:

100
200
300
400
500

seq.txt:

abc
objw
cde
efg
xyz
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
prashanta_himalay
  • 149
  • 2
  • 2
  • 9

1 Answers1

1

readarray places a whitespace at end of each variable, which seems to be causing problems with the sed command.

One elegant way get rid of a trailng whitespace is to pipe the string to xargs:

string2=$(echo ${t1Gad[$COUNTER]} | xargs)
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65