Linux 24.04下Makefile导出指定GPG密钥失效问题求助
问题分析与解决方案
问题根源
你遇到的核心问题是Makefile的每个目标命令都在独立的Shell进程中执行,choose_gpg_key目标里通过read定义的input_email等变量,只存在于该目标对应的Shell进程中,无法被export_import_gpg_keys目标的Shell进程读取。当$(input_email)为空时,gpg --export会默认导出所有密钥,这就是你看到的现象。
方案一:修复Makefile的变量传递问题
要让变量在多个命令间共享,需要把相关命令放在同一个Shell进程中执行(用\连接多行命令),同时注意Makefile中Shell变量需要用$$转义(避免被Make解析为自身变量)。修改后的Makefile可以合并步骤,同时直接配置Git项目的密钥:
configure_gpg_for_git: @echo "\nYour current GPG list:" @gpg --list-secret-keys --keyid-format=long @echo "Please choose one GPG ID and input the corresponding information to continue." @read -p "Choose email: " input_email; \ read -p "GPG ID: " input_gpg_key; \ read -p "Your name: " input_full_name; \ # 导出/导入密钥(如果确实需要的话) gpg --export $$input_email > gpg-public.key; \ gpg --import gpg-public.key; \ gpg --export-secret-key $$input_email > gpg-private.key; \ gpg --import gpg-private.key; \ # 直接配置当前Git项目的签名密钥 git config user.name "$$input_full_name"; \ git config user.email "$$input_email"; \ git config user.signingkey "$$input_gpg_key"
执行时只需运行:
make configure_gpg_for_git
方案二:更简洁的Git项目级配置(推荐)
实际上你不需要导出/导入密钥——既然机器上已经存在多个GPG密钥,直接给每个Git项目单独配置签名密钥即可,完全不需要Makefile:
- 进入项目A的根目录,执行以下命令(替换为对应密钥信息):
git config user.name "你的项目A用户名" git config user.email "项目A关联邮箱" git config user.signingkey "GPG密钥A的ID"
- 进入项目B的根目录,执行类似命令(替换为项目B的信息):
git config user.name "你的项目B用户名" git config user.email "项目B关联邮箱" git config user.signingkey "GPG密钥B的ID"
这样Git在该项目中提交时,会自动使用配置好的GPG密钥签名,无需额外操作。如果需要全局默认密钥,保留git config --global的配置即可,项目级配置会覆盖全局配置。
内容的提问来源于stack exchange,提问作者Tommy Hoang
相关产品推荐
相关产品推荐

