-
-
Save cmbuckley/00c360e0f74b5bedb418866b6b7ed9f5 to your computer and use it in GitHub Desktop.
Use 1Password to copy a password to the clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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