pack.sh
#!/bin/bash
if [ "$1" == "" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo "打包应用程序依赖库"
echo
echo "用法: ./pack.sh -f 应用程序文件 [-p 依赖库目标目录] [-a 0|1]"
echo
echo "示例: ./pack.sh -f test -p lib"
echo " ./pack.sh -f test -p lib -a 0"
echo
echo "选项:"
echo " -f : 指定要打包的应用程序文件"
echo " -p : 指定应用程序文件依赖库要打包存放的目录(选填), 默认存放在当前目录"
echo " -a : 指定是否只打包直接动态依赖库(选填), 值为: [0, 1], 默认为1打包所有"
echo
exit 0
fi
#################### 解析参数-f, -p, -a [0,1] ####################
procFile= # 应用程序文件
libPath= # 依赖库要存放的目录
packAll=1 # 是否打包所有依赖库
function parseParams() {
foundProcFile=0
foundLibPath=0
foundPackAll=0
for item in $@ ; do
if [ $foundProcFile == 1 ]; then
procFile="$item"
foundProcFile=2
fi
if [ $foundLibPath == 1 ]; then
libPath="$item"
foundLibPath=2
fi
if [ $foundPackAll == 1 ]; then
packAll="$item"
foundPackAll=2
fi
if [ "$item" == "-f" ]; then # 应用程序文件, 例如: /home/jaron/cxx_test
foundProcFile=1
fi
if [ "$item" == "-p" ]; then # 依赖库要存放的目录(选填), 默认脚本所在目录, 例如: lib
foundLibPath=1
fi
if [ "$item" == "-a" ]; then # 是否打包所有依赖库(选填), 默认打包所有, 值为0或1
foundPackAll=1
fi
done
}
parseParams $@
# step1. 判断应用程序文件
if [ "$procFile" == "" ]; then
echo "缺少参数-f, 应用程序文件, 如: /home/jaron/cxx_test"
exit 0
fi
if [ ! -f "$procFile" ]; then
echo "应用程序文件'$procFile'不存在"
exit 0
fi
# step2.创建依赖库目录
if [ "$libPath" == "" ]; then
libPath=./
else
mkdir -p "$libPath"
if [ ! -d "$libPath" ]; then
libPath=./
fi
fi
# step3.查找依赖库
depList=($(ldd "$procFile" | grep -o "/.*" | grep -o "/.*/[^[:space:]]*"))
# step4.拷贝依赖库
for dep in ${depList[@]}; do
if [ -f $dep ]; then
name=$(basename $dep)
result=$(readelf -d "$procFile" | grep "\[$name\]")
if [ $packAll == 1 ] || [ "$result" != "" ]; then
echo "依赖库: $dep"
cp "$dep" "$libPath"
fi
fi
done
用法:./pack.sh -f 应用程序文件 [-p 依赖库目标目录] [-a 0|1]
。
示例:
./pack.sh -f test -p lib
./pack.sh -f test -p lib -a 0