user2064000 user2064000 - 6 months ago 17
Bash Question

Self-extracting script in sh shell

How would I go about making a self extracting archive that can be executed on

sh
?

The closest I have come to is:

extract_archive () {
printf '<archive_contents>' | tar -C "$extract_dir" -xvf -
}


Where
<archive_contents>
contains a tarball with null characters,
%
,
'
and
\
characters escaped and enclosed between single quotes.

Is there any better way to do this so that no escaping is required?

(Please don't point me to
shar
,
makeself
etc. I want to write it from scratch.)

Answer

Alternative variant is to use marker for end of shell script and use sed to cut-out shell script itself.

Script selfextract.sh:

#!/bin/bash

sed '0,/^#EOF#$/d' $0 | tar zx; exit 0
#EOF#

How to use:

# create sfx
cat selfextract.sh data.tar.gz >example_sfx.sh

# unpack sfx
bash example_sfx.sh