1

I'm trying to use the following code to update a file within a kubernetes pod/container

I'm setting some variables;

searchline='<Logger name="com.mycompany" level="INFO" additivity="false">'

newline='<Logger name="com.mycompany" level="DEBUG" additivity="false">'

then using the following command;

kubectl exec mypod -- bash -c "cp conf/log4j2.xml conf/log4j2.xml.bkup && sed -i "s/$searchline/$newline/g" conf/log4j2.xml"

sed: -e expression #1, char 8: unterminated `s' command

However, if I shell into the pod and manually run the same sed command

sed "s/$searchline/$newline/g" conf/log4j2.xml (not in the bash -c "" format) it runs as it should.

Not sure why it doesn't work within the bash -c, probably has something to do with the double quotes in the bash -c command..

any help would be appreciated.

Thomas Hansen
  • 775
  • 1
  • 6
  • 17
RobA
  • 51
  • 3

1 Answers1

0

I figured it out. the following works;

bash -c "cp conf/log4j2.xml conf/log4j2.xml.bkup && sed -i 's/$searchline/$newline/g' conf/log4j2.xml"

seems when using sed in the bash -c command you don't need do use double quotes for the variable expansion like you normally would.

RobA
  • 51
  • 3
  • 1
    That's not true; you should definitely quote, but you can't use the same outer and inner quotes. Somewhat surprisingly, perhaps, but obviously if you think about it, single quotes _inside_ double quotes are just another regular character, and the double quotes quote everything inside the single quotes too. Once the shell you run with `bash -c` receives and parses the quoted string, the text inside the single quotes has already been processed by the invoking shell. – tripleee Apr 07 '21 at 13:03
  • @tripleee, so how would you suggest this be done? – RobA Apr 08 '21 at 13:27
  • The solution is correct, it's just that the conclusion isn't. You _are_ using double quotes but superficially the single quotes work fine in this context as long as you know what you are doing (i.e. you are not trying to use variables which are only defined inside the double quotes). See also the duplicate for more elaboration. – tripleee Apr 08 '21 at 13:36