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?

5
  • 2
    I can’t reproduce this. Is that the exact code? You don’t have something like echo "${#LINES}"? Commented Apr 10, 2019 at 9:18
  • 2
    Also can't reproduce - echo #2 works as expected, printing the 'some text' lines Commented Apr 10, 2019 at 9:25
  • 1
    Is this a duplicate of stackoverflow.com/questions/1780483/…? Does the script work if you replace $LINES with a differently named variable? Commented Apr 10, 2019 at 9: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. Commented Apr 10, 2019 at 9:45
  • 1
    ^ spot on indeed. I feel like a certified idiot. Lesson learned I suppose. Commented Apr 12, 2019 at 10:04

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.