【bash】linux中打包某个可执行文件及其依赖文件
#!/bin/bash
# 脚本用于打包可执行文件及其依赖库,并打印详细信息
# 使用方法: ./package_executable.sh <可执行文件名>
# 检查输入参数
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <executable_name>"
exit 1
fi
EXECUTABLE_NAME=$1
EXECUTABLE=$(which "$EXECUTABLE_NAME")
# 检查可执行文件是否存在
if [ -z "$EXECUTABLE" ]; then
echo "Error: Executable '$EXECUTABLE_NAME' not found in PATH."
exit 1
fi
OUTPUT_PACKAGE="${EXECUTABLE_NAME}_package.tar.gz"
PACKAGE_DIR="package_temp"
# 创建临时目录
rm -rf $PACKAGE_DIR
mkdir -p $PACKAGE_DIR
# 复制可执行文件
cp "$EXECUTABLE" "$PACKAGE_DIR/"
# 获取可执行文件的依赖库
DEPENDENCIES=$(ldd "$EXECUTABLE" | awk '{if (match($3, "/")) print $3}')
# 初始化变量
COPIED_LIBS=()
# 复制依赖库
for LIB in $DEPENDENCIES; do
if [ -f "$LIB" ]; then
cp --parents "$LIB" "$PACKAGE_DIR" 2>/dev/null
if [ $? -eq 0 ]; then
COPIED_LIBS+=("$LIB")
else
echo "Warning: Failed to copy library $LIB"
fi
else
echo "Warning: Library $LIB does not exist."
fi
done
# 打印对比信息
echo "\n===== Dependency Analysis ====="
echo "Libraries listed by ldd:"
echo "$DEPENDENCIES"
echo "\nLibraries successfully copied:"
echo "${COPIED_LIBS[@]}"
# 打包目录为 tar.gz 文件
tar -czvf "$OUTPUT_PACKAGE" -C "$PACKAGE_DIR" .
# 清理临时目录
rm -rf $PACKAGE_DIR
# 打包完成
echo "\nPackage created: $OUTPUT_PACKAGE"