Comments on Replacing the shebang in a script
Parent
Replacing the shebang in a script
In a Bash script and/or at the command line, given that $file is the path to an executable text file with a shebang, and $env is a valid shebang, I want to replace the existing shebang in the file with the new one. Is there a standard or well-known way?
I thought of echoing the new shebang and then tailing the rest of the file, but this requires explicitly making a temporary file and replacing the original with it (and possibly fixing mode/owner).
I also thought of using sed, but I can't quite figure it out given that shebangs generally contain multiple forward slashes which interfere with the regex syntax. It also seems like overkill since only the first line needs to be considered for replacement.
Post
Sed has more commands than just s! You can replace the first line of the input with a new value using the c command, without having to write any regular expressions.
sed "1c\\$env" "$file"

1 comment thread