我正在尝试在不使用 sudo 权限的情况下自动安装 git,一个不错(但缓慢)的解决方法是安装 Xcode,它与 git 捆绑在一起,可以xcode-select --install
由标准用户调用
#!/bin/bash
# check if user has git installed
which git &> /dev/null
OUT=$?
sleep 3
# if output of git check is not 0(not foud) then run installer
if [ ! $OUT -eq 0 ]; then
xcode_dialog () {
XCODE_MESSAGE="$(osascript -e 'tell app "System Events" to display dialog "Please click install when Command Line Developer Tools appears"')"
if [ "$XCODE_MESSAGE" = "button returned:OK" ]; then
xcode-select --install
else
echo "You have cancelled the installation, please rerun the installer."
fi
}
xcode_dialog
fi
# get xcode installer process ID by name and wait for it to finish
until [ ! "$(pgrep -i 'Install Command Line Developer Tools')" ]; do
sleep 1
done
echo 'Xcode has finished installing'
which git &> /dev/null
OUT=$?
if [ $OUT = 0 ]; then
echo 'Xcode was installed incorrectly'
exit 1
fi
然而,我的until
语句被完全忽略,并且几乎一旦XCODE_MESSAGE
返回 OK 就会触发对 git 的第二次检查。有人知道如何更好地实现等待安装程序完成的逻辑吗?
答案1
我会稍微改变您在脚本中遵循的方法:检查“git”是否存在,而不是检查安装过程是否未运行:
#!/bin/bash
# check if user has git installed and propose to install if not installed
if [ "$(which git)" ]; then
echo "You already have git. Exiting.."
exit
else
XCODE_MESSAGE="$(osascript -e 'tell app "System Events" to display dialog "Please click install when Command Line Developer Tools appears"')"
if [ "$XCODE_MESSAGE" = "button returned:OK" ]; then
xcode-select --install
else
echo "You have cancelled the installation, please rerun the installer."
# you have forgotten to exit here
exit
fi
fi
until [ "$(which git)" ]; do
echo -n "."
sleep 1
done
echo ""
echo 'Xcode has finished installing'