Home > Back-end >  Insert string/source command after #!/bin/bash line in a bash file
Insert string/source command after #!/bin/bash line in a bash file

Time:07-26

I'm trying to insert a certain string after the #!/bin/bash line in a separate bash file but I'm running into issues with my sed statement not parsing through the characters correctly. I'm basing my example off of solutions here https://unix.stackexchange.com/questions/121161/how-to-insert-text-after-a-certain-string-in-a-file

So for example, I have a sed statement that is trying to write a source command to scriptOne.sh:

sed '/#!/bin/bash/a source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

I would like scriptOne.sh to go from this:

#!/bin/bash

to this after running my script:

#!/bin/bash

source /root/documents/folder/scriptTwo.sh

The sed command doesn't seem to work I think because of the extra slashes and characters it's having trouble separating from an actual string vs regex characters. Ideally I would also like to insert an extra blank line between the #!/bin/bash and source command, but my main goal is just to insert that source command under the #!/bin/bash.

Update:

I tried this in my script (just another random script located in /home/student/Desktop):

#!/bin/bash

sed '\~#!/bin/bash~ a\
\
source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh

but when I run it, scriptOne.sh does not get altered.

CodePudding user response:

You may use sed like this:

sed -i.bak '\~#!/bin/bash~ a\
\
source /root/documents/folder/scriptTwo.sh' /root/home/scriptOne.sh
  • Related