ldd2chroot - A script to extract packagesΒΆ

Updated: May 07, 2024

At last I got some time to blog, and I did something with chroot. Here is a script which will extract ldd dependency library packages(.debs) to chroot directory. Here is the steps it follows,

  1. For the given command, get the shared libraries.

  2. Then get the packages which will give the shared libraries.

  3. and download those shared libraries and extract in the given chroot directory.

I hope it will be useful to package maintainers.

#!/bin/bash
# ldd2chroot - A script to extract packages
# Author: mohan43u


USAGE="[usage]
     ldd2chroot [-i chrootdir] [-p] [-h] cmd_or_pkg [...]"
HELP="${USAGE}
[description]
     -i chrootdir    Install pkgs in 'chrootdir'
     -p              'chd_or_pkg' will be package name
     -h              Print this help
     cmd_or_pkg      Command name or package name(only for -p)"

executeldd()
{
ldd $(which "${1}")
}

getsharedlibs()
{
tr '\t' ' ' |
tr -s ' ' '\n' |
grep '^/'
}

getlibpkgs()
{
while read LIB; do dpkg -S "${LIB}"; done
}

getpkgs()
{
cut -d':' -f1 | sort | uniq
}

extractpkg()
{
for PKG
do
     echo "[starting apt-get for ${PKG}]"
     apt-get clean
     apt-get --reinstall --download-only --yes install "${PKG}"
     DEBFILE=$(find /var/cache/apt/archives -name '*.deb')
     cp -p ${DEBFILE} $(pwd)
     test ! -z "${CHROOTDIR}" && echo -e "[extracting ${DEBFILE} to ${CHROOTDIR}]" &&
     dpkg -X "${DEBFILE}" "${CHROOTDIR}"
done
}

while getopts 'i:ph' OPTIONS
do
     case "${OPTIONS}" in
             i) CHROOTDIR="${OPTARG}";;
             p) PKGARGS="1";;
             h) echo -e "${HELP}" && exit 0;;
             \?) echo -e "${USAGE}" && exit 1;;
     esac
done
shift $((OPTIND - 1))
test -z "${@}" && echo -e "${USAGE}" && exit 1

for ARG
do
     if test -z "${PKGARGS}"
     then
             LDDOUTPUT=$(executeldd "${ARG}")
             echo -e "[ldd]\n${LDDOUTPUT}"
             SHAREDLIBS=$(echo -e "${LDDOUTPUT}" | getsharedlibs)
             SHAREDLIBS="$(which ${ARG})\n${SHAREDLIBS}"
             echo -e "[sharedlibs]\n${SHAREDLIBS}"
             LIBPKGS=$(echo -e "${SHAREDLIBS}" | getlibpkgs)
             echo -e "[required shared library packages]\n${LIBPKGS}"
             PKGS=$(echo -e "${LIBPKGS}" | getpkgs)
             echo -e "[required pkgs for apt-get]\n${PKGS}"
     else
             PKGS="${ARG}"
     fi

     extractpkg ${PKGS}
done

If someone improving this, let me know, so that I can also use the changes.