1

I'm trying to create a bash script that parses some multi-line strings, and I also keep a log file for what it's doing.

I use tee -a to output the current step to both stdout and the log file. When I do this, the multi-line string variable changes completely, and I can't for the life of me figure out why this happens.

Can anyone please shed some light on this?

e.g. using this script:

#!/bin/bash
#


LINES=""
LINES="$(echo -e "$LINES\\n some text 1")"
LINES="$(echo -e "$LINES\\n some text 2")"
LINES="$(echo -e "$LINES\\n some text 3")"
LINES="$(echo -e "$LINES\\n some text 4")"
LINES="$(echo -e "$LINES\\n some text 5")"

echo "#1"
echo "'"
echo "$LINES"
echo "'"

echo -e "\nnow doing thing A" | tee -a "log.txt"

echo "#2"
echo "'"
echo "$LINES"
echo "'"


echo ""


LINES=""
LINES="$(echo -e "$LINES\\n some text 1")"
LINES="$(echo -e "$LINES\\n some text 2")"
LINES="$(echo -e "$LINES\\n some text 3")"
LINES="$(echo -e "$LINES\\n some text 4")"
LINES="$(echo -e "$LINES\\n some text 5")"

echo "#3"
echo "'"
echo "$LINES"
echo "'"

echo -e "\nnow doing thing B"
echo -e "\nnow doing thing B" >> "log.txt"

echo "#4"
echo "'"
echo "$LINES"
echo "'"

This gives me the following output:

#1
'

 some text 1
 some text 2
 some text 3
 some text 4
 some text 5
'

now doing thing A
#2
'
61
'

#3
'

 some text 1
 some text 2
 some text 3
 some text 4
 some text 5
'

now doing thing B
#4
'

 some text 1
 some text 2
 some text 3
 some text 4
 some text 5
'

why is echo #2 suddenly different?

Jon
  • 3,573
  • 2
  • 17
  • 24
Adriaantje
  • 23
  • 4
  • 2
    I can’t reproduce this. Is that the *exact* code? You don’t have something like `echo "${#LINES}"`? – Biffen Apr 10 '19 at 09:18
  • 2
    Also can't reproduce - echo #2 works as expected, printing the 'some text' lines – Jon Apr 10 '19 at 09:25
  • 1
    Is this a duplicate of https://stackoverflow.com/questions/1780483/lines-and-columns-environmental-variables-lost-in-a-script? Does the script work if you replace $LINES with a differently named variable? – Jon Apr 10 '19 at 09:29
  • 2
    ^ Spot on I think. The real lesson is to not use upper case for your private variables so as to avoid clobbering reserved system variables. More specifically, the `LINES` variable will be replaced by Bash if you have `shopt -s checkwinsize` enabled. – tripleee Apr 10 '19 at 09:45
  • 1
    ^ spot on indeed. I feel like a certified idiot. Lesson learned I suppose. – Adriaantje Apr 12 '19 at 10:04

0 Answers0