0

I tried to use the bash string native manipulation for substituting string with my shell variables.

var1='123'
var2='2018-01-01'
var3='2018-01-02'
var4='myfunction('var1','var2','var3')'

var5=${var4/var1/$var1}
echo $var5

var5=${var5/var2/$var2}
echo $var5

var5=${var5/var1/$var3}
echo $var5

Expected output:

myfunction('123','var2','var3')
myfunction('123','2018-01-01','var3')
myfunction('123','2018-01-01','2018-01-02')

Actual output with jumbled strings:

myfunction('123','var2','var3')
myfunction('123','2018-01-01','var3')
')function('123','2018-01-01','2018-01-02

Here the last two characters shift at the beginning and I lose the first two characters of the string. I can use SED for the same. But I am just trying to figure out why will the bash native string manipulation not work as expected. Is it because I am doing multiple substitutions ?

Thanks for your help.

3
  • Can't reproduce your error. But try quoting your assignements: var5="${var4/var1/$var1}" as well as echo "$var5".
    – markgraf
    Nov 22, 2019 at 15:30
  • Your third substitution should be var5=${var5/var3/$var3} and if you want to keep the single quotes in myfunction('var1','var2','var3'), you should define var4 using var4="myfunction('var1','var2','var3')". But I can't see a reason why the output should be jumbled.
    – Freddy
    Nov 22, 2019 at 15:30
  • 1
    That's not the output of that script. First of all, you're never replacing var3, but var1 twice. Second, your var4 does not have any single quotes within it, but somehow the output has them anyway. Please post the exact script you use when asking for help online, the details matter.
    – ilkkachu
    Nov 22, 2019 at 16:15

1 Answer 1

2

There is a carriage return (CR) character at the end of var3 content. After it gets printed without immediately following newline character (line feed, LF), the remaining part of the line is printed from the left edge, overwriting the already printed beginning of the line.

Unix standard of line ending is LF, not CR LF.

Rewrite the script line where the variable is defined or use dos2unix on the file.

1
  • dos2unix solved the problem!! Thanks so much @Kamil :)
    – Jenny
    Nov 22, 2019 at 18:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .