Windows下Git Bash脚本带指定Profile启动Chrome.exe的问题
解决Git Bash中启动Chrome指定配置文件的问题
问题背景
需要在Windows的Git Bash中通过Shell脚本启动Chrome,同时指定特定配置文件和目标URL,且不想将chrome.exe加入系统PATH。目前不带Profile参数时脚本可正常运行,但添加参数后Chrome会使用默认配置文件,还会错误解析URL,尝试多种转义方式均无效。
错误脚本示例
echo ---------------------------------------- function openSomeUrl() { local URL="https://github.com/chipbite/" # some url local BROWSER='/c/Program Files (x86)/Google/Chrome/Application/chrome.exe' echo "$BROWSER" "$URL" # so for some URLs, I want a private profile, for others my work profile # I have without success tried e g # (1) adding the switches separately (ie $BROWSER $SWITCHES $URL), # (2) to the BROWSER variable/command and # (3) as a part of/prefix to the $URL variable, as below, here: if ( echo $URL | grep -q chipbite ); then URL="--profile-directory='Profile 1' $URL" else # URL="--profile-directory='Default' $URL" echo default fi echo "$BROWSER" $URL # 1 - without quotes # "$BROWSER" $URL # --> /c/Program Files (x86)/Google/Chrome/Application/chrome.exe --profile-directory='Profile 1' https://github.com/chipbite/ # opens in default profile, tries url-> 1' -- as in the end of 'Profile 1' echo "$BROWSER" "$URL" # 2 - with quotes. prints exactly same as 1, but that is since they are not escaped. "$BROWSER" $URL } openSomeUrl echo ----------------------------------------
问题原因
核心是参数传递的引号处理错误:把配置参数和URL拼到同一个变量里,且用了Git Bash风格的单引号,而Windows程序(Chrome)不识别这种单引号,导致Chrome把'Profile 1'里的单引号当成参数的一部分,无法正确识别配置目录,还错误地把1'解析为URL的一部分。
正确解决方案
方案1:拆分参数单独传递
将配置参数单独存储,调用时分别传递给Chrome,确保带空格的参数被正确包裹:
echo ---------------------------------------- function openSomeUrl() { local URL="https://github.com/chipbite/" local BROWSER='/c/Program Files (x86)/Google/Chrome/Application/chrome.exe' local PROFILE_SWITCH="" echo "$BROWSER" "$URL" if echo "$URL" | grep -q chipbite; then # 去掉单引号,直接用空格分隔参数内容 PROFILE_SWITCH="--profile-directory=Profile 1" else PROFILE_SWITCH="--profile-directory=Default" echo default fi # 关键:分别传递浏览器路径、配置参数、URL,每个带空格的参数用双引号包裹 "$BROWSER" "$PROFILE_SWITCH" "$URL" } openSomeUrl echo ----------------------------------------
方案2:使用Windows的start命令
如果直接调用仍有问题,可适配Windows原生的start命令,确保参数被正确解析:
echo ---------------------------------------- function openSomeUrl() { local URL="https://github.com/chipbite/" # 也可以用Git Bash风格路径:'/c/Program Files (x86)/Google/Chrome/Application/chrome.exe' local BROWSER="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" local PROFILE_SWITCH="" if echo "$URL" | grep -q chipbite; then PROFILE_SWITCH="--profile-directory=Profile 1" else PROFILE_SWITCH="--profile-directory=Default" echo default fi # start命令第一个参数为窗口标题,留空即可;所有带空格的内容用双引号包裹 start "" "$BROWSER" "$PROFILE_SWITCH" "$URL" } openSomeUrl echo ----------------------------------------
内容的提问来源于stack exchange,提问作者mawi
相关产品推荐
相关产品推荐

