29 Jan 2010

packing several unix files into one executable shell script (simple installer)

These 2 scripts are able to pack a directory into a shell script. The shell script can then be executed on another system and will extract the packed files into a target directory, unix permissions will be preserved (tar is used).

What you need:
- sh
- readlink
- dirname
- basename
- tar
- gzip
- uuencode
- uudecode
- cat
- chmod

pack.sh

#!/bin/sh

# $1 is source directory or file
if [ -z "$1" -o ! -e "$1" ]; then
echo "Usage: $0 <target-directory-or-file> <destination-file>"
exit 1
fi

# $2 is dst file
if [ -z "$2" ]; then
echo "Usage: $0 <target-directory-or-file> <destination-file>"
exit 1
fi

# Absolute path to this script. /home/user/bin/foo.sh
SCRIPT=$(readlink -f $0)
# Absolute path this script is in. /home/user/bin
SCRIPTPATH=`dirname $SCRIPT`

WORKINGDIR="$1"
TARGET="."
if [ -f "$WORKINGDIR" ]; then
WORKINGDIR=`dirname $WORKINGDIR`
TARGET=`basename $1`
fi

# pack directory or files into a uuencoded tar.gz archive
cat "$SCRIPTPATH/execute.sh" > "$2"
echo "w $WORKINGDIR $TARGET"
tar -c -C "$WORKINGDIR" -zf - "$TARGET" | \
uuencode "embedded-files.tar.gz" >> "$2"

chmod u+x,g+x "$2"


execute.sh
#!/bin/sh

# $1 is target directory
if [ -z "$1" ]; then
echo "Usage: $0 <target-directory>"
exit 1
fi

# create target directory (if not exists) or exit if we fail
mkdir -p "$1"
if [ $? != 0 ]; then
echo "Failed to create target directory"
exit 3
fi

# Absolute path to this script. /home/user/bin/foo.sh
SCRIPT=$(readlink -f $0)
# Absolute path this script is in. /home/user/bin
SCRIPTPATH=`dirname $SCRIPT`

cd $1;
uudecode "$SCRIPTPATH/$(basename $0)"
tar -xzf "embedded-files.tar.gz"
rm "embedded-files.tar.gz"

exit 0;