Skip to content

Instantly share code, notes, and snippets.

@cmbuckley
Last active September 13, 2021 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmbuckley/00c360e0f74b5bedb418866b6b7ed9f5 to your computer and use it in GitHub Desktop.
Save cmbuckley/00c360e0f74b5bedb418866b6b7ed9f5 to your computer and use it in GitHub Desktop.
Use 1Password to copy a password to the clipboard
#!/bin/bash
check_session() {
[ -f $HOME/.op/token ] && export OP_SESSION_my="$(cat $HOME/.op/token)"
# attempt sign in if session is not active
if ! op get account &> /dev/null; then
signin
check_session
fi
}
signin() {
op signin my | \
grep 'export' | \
awk -F\" '{print $2}' > $HOME/.op/token
}
usage() {
echo "Usage: p [-o OUTFILE] ITEM" >&2
exit 1
}
outfile=
while getopts ":o:" opt; do
case "$opt" in
o)
outfile=$OPTARG
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
[ $# -eq 0 ] && usage
check_session
out="$(op get item "$1")"
category="$(op list templates | jq -r '.[] | select(.uuid=="'$(jq -r .templateUuid <<< "$out")'") | .name')"
# check for supported 1Password category
case $category in
Login)
path='.details.fields | .[] | select(.type=="P") | .value'
;;
Password)
path='.details.password'
;;
*)
[ -n "$category" ] && echo "Cannot read password from ‘${category}’ entries" >&2
exit 1
;;
esac
password=$(jq -r "$path" <<< "$out" | tr -d '\n')
if [ -z "$outfile" ]; then
# try to put it on the clipboard
case "$OSTYPE" in
darwin*)
pbcopy <<< "$password"
;;
cygwin*)
printf '%s' "$password" > /dev/clipboard
;;
*)
if command -v xclip &> /dev/null; then
xclip -selection clipboard -i <<< "$password"
elif command -v xsel; then
xsel --clipboard <<< "$password"
else
echo 'Cannot find supported clipboard' >&2
exit 1
fi
;;
esac
did='copied to clipboard'
else
printf '%s' "$password" > "$outfile"
did="written to ‘${outfile}’"
fi
echo "Password for $(jq -r '.overview.title' <<< "$out") $did"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment