Tuesday, June 11, 2013

Launch Chrome by Profile Name

Chrome allows you to launch it under a given profile if you give it an argument of --profile-directory="Directory Name". The directory names are "Default", "Profile 1", "Profile 2", etc.. Obviously this is not super convenient as you need to know the profile directory that goes with a given profile name. Here is a script that allows you to launch Chrome by profile name instead, followed by some bash code to allow bash auto-completion of profile names. First the gchrome script:
#!/usr/bin/env bash
if [ $# -eq 0 ]; then
exec google-chrome &
exit 0
else
for preffile in ~/.config/google-chrome/{Default,Profile*}/Preferences; do
# The profile name appears to always be the last "name:" in the json
# of the Preferences file. Yes, fragile, but appears to work for now.
profname=$(grep \"name\" "$preffile" | tail -1 | sed -e 's/.*"\([^"]*\)",\?$/\1/')
if [ "$1" == "$profname" ]; then
profdir=$(echo "$preffile" | sed -e 's|^.*google-chrome/\([^/]*\)/Preferences$|\1|')
echo "Going to launch with profile directory: $profdir"
exec google-chrome --profile-directory="$profdir" &
exit 0
fi
done
# didn't find that profile name
echo "Profile named $1 not found!"
exit 1
fi
view raw gchrome hosted with ❤ by GitHub
and next, the bash completion code. Throw this in .bashrc or somewhere:
function _gchrome_profile() {
local IFS=$'\n'
local param=${COMP_WORDS[COMP_CWORD]}
local profiles=""
local preffile
for preffile in ~/.config/google-chrome/{Default,Profile*}/Preferences; do
# The profile name appears to always be the last "name:" in the json
# of the Preferences file. Yes, fragile, but appears to work for now.
local name=$(grep \"name\" "$preffile" | tail -1 | sed -e 's/.*"\([^"]*\)",\?$/\1/')
profiles="$profiles
$name"
done
COMPREPLY=( $(compgen -W "$profiles" "$param") )
}
complete -F _gchrome_profile gchrome
view raw .bashrc hosted with ❤ by GitHub
Note that this relies on a certain layout of the Preferences file json which I have found to hold so far, however, it wouldn't be too surprising to find json that breaks it. This should work for Chrome on most Linux installs. This could probably be adjusted to work on OS X but the config file is located elsewhere. Enjoy.