Search code examples
bashexecutablebinaryfilesediting

Edit an executable with bash without recompiling it?


I'm trying to write a script for editing an executable (e.g. /bin/bash) in this way:

Search for a string - Replace old string with new string - Save changes to original file (obviously I'm trying on a copy of /bin/bash, for security reason)

My string is a single word. How can I do it?


Solution

  • You can easily modify a string in a binary file with sed but as noted in the comments it will most often only work when old and new string have the same length. With bash for example:

    $ cp /bin/bash .
    $ strings bash  | grep such
    describe_pid: %ld: no such pid
        it creates, on systems that allow such control.
              such as cd which change the current directory.
    %s: no such job
    $ sed 's,no such job,no such boj,' -i bash
    $ ./bash --noprofile --norc
    bash-4.3$ kill %3333
    bash: kill: %3333: no such boj
    

    -i for sed is not in POSIX so if you want to achieve maximum portability:

    $ cp /bin/bash .
    $ sed 's,no such job,no such boj,' bash > bash.bak
    $ mv bash.bak bash
    $ chmod +x ./bash
    $ ./bash --noprofile --norc
    bash-4.3$ kill %3333
    bash: kill: %3333: no such boj