Insert string/source command after #!/bin/bash line in a bash file


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

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

sed '/#!/bin/bash/a source /root/documents/folder/' /root/home/

I would like to go from this:


to this after running my script:


source /root/documents/folder/

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.


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


sed '\~#!/bin/bash~ a\
source /root/documents/folder/' /root/home/

but when I run it, does not get altered.


You may use sed like this:

sed -i.bak '\~#!/bin/bash~ a\
source /root/documents/folder/' /root/home/

Answered By – anubhava

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published