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

Issue

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.

Solution

You may use sed like this:

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

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