0

I'm trying to create a script to config rc.local file. I need to insert multiline command with variable before exit 0 line.

For example,

  • the variable VARIABLE=31
  • original rc.local file:
#!/bin/bash
#
# rc.local
#
# blah blah...

exit 0
  • desired rc.local after executing setup.sh:
#!/bin/bash
#
# rc.local
#
# blah blah...

if [ `gpio read 31` = 1 ]; then  # this 31 is the value of VARIABLE
  do_something
fi

exit 0

This is my attemption:

VARIABLE=31
sed "/^exit 0/i \
if [ \`gpio read $VARIABLE\` = 1 ]; then \
  do_something \
fi" -i rc.local

But the result rc.local is

#!/bin/bash
#
# rc.local
#
# blah blah...

if [ `gpio read 31` = 1 ]; then do_something fi
exit 0

I cannot get the linebreak.

And if I use \n, it errors with

unknown command: `m'

How to solve this?

0

That's because you're using double-quotes (") for your sed command.

The backslashes get thus interpreted and consumed by the running shell, just like it does for those preceding the backticks, which I believe you used precisely to make your running shell not interpret those backticks itself.

To solve this, you need to use two backslashes (\\) only for the backslashes preceding the newlines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.