2

Trying to remove a # sign from a single line in a file. The line is currently

#/usr/bin/tvservice -o
if [[ '$grep tvservice /etc/rc.local' =~ ^# ]] ;
then sed -i '/^#.* tvservice /s/^#//' /etc/rc.local ;
else echo 1 fi

Trying to test if this command will work before I add it to a script. When I run it I get a > symbol and have to stop execution with Ctrl+C

Am I not passing a string to grep correctly or what? I'm fairly new to this.

3

I suggest you test without sed's -i flag first - or use a local copy of the rc.local file.

You don't need to test for the string's presence, but if you do, then the correct way to substitute grep's output would be "$(grep tvservice /etc/rc.local)" - the way you have written it tests the literal string $grep tvservice /etc/rc.local

However, a better way IMHO would be to grep for the whole pattern and use grep's exit status directly, avoiding the shell regex test altogether:

if grep -q '^#.*tvservice' /etc/rc.local; then 
  sed -i '/^#.*tvservice/ s/^#//' /etc/rc.local
else 
  echo 1
fi

(I removed the spaces around the pattern, since your sample text doesn't have them).

| improve this answer | |
  • Meh, just a minute faster than me... – Byte Commander Feb 24 '18 at 15:25
  • I ran the command in this form and am getting 2 as output and then nothing. It doesn't really exit the script properly, any clues ? if grep -q '^#/*tvservice' /etc/rc.local; then echo 1 sed -i '/^#.*tvservice/ s/^#//' /etc/rc.local else echo 2 sed -e '/tvservice/ s/^#*/#/' fi – Kylar Stern Feb 24 '18 at 19:29
  • This is the state of the file currently {code} #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. #Disable HDMI #/usr/bin/tvservice -o exit 0 {code} – Kylar Stern Feb 24 '18 at 19:33
  • I saw for second sed I didn't give it a file to edit. Fixed it the command runs and exits out but I get the "2" as output still which means that it skips the "then" where it's supposed to remove the # from that line. – Kylar Stern Feb 24 '18 at 19:46

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.