opswd 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #autoload
  2. # opswd puts the password of the named service into the clipboard. If there's a
  3. # one time password, it will be copied into the clipboard after 10 seconds. The
  4. # clipboard is cleared after another 20 seconds.
  5. function opswd() {
  6. if [[ $# -lt 1 ]]; then
  7. echo "Usage: opswd <service>"
  8. return 1
  9. fi
  10. local service=$1
  11. # If not logged in, print error and return
  12. op user list > /dev/null || return
  13. local password
  14. # Copy the password to the clipboard
  15. if ! password=$(op item get "$service" --fields password 2>/dev/null); then
  16. echo "error: could not obtain password for $service"
  17. return 1
  18. fi
  19. echo -n "$password" | clipcopy
  20. echo "✔ password for $service copied to clipboard"
  21. # If there's a one time password, copy it to the clipboard after 10 seconds
  22. local totp
  23. if totp=$(op item get --otp "$service" 2>/dev/null) && [[ -n "$totp" ]]; then
  24. sleep 10 && echo -n "$totp" | clipcopy
  25. echo "✔ TOTP for $service copied to clipboard"
  26. fi
  27. (sleep 20 && clipcopy </dev/null 2>/dev/null) &!
  28. }
  29. # TODO: 2022-03-26: Remove support for op CLI 1
  30. autoload -Uz is-at-least
  31. is-at-least 2.0.0 $(op --version) || {
  32. print -ru2 ${(%):-"%F{yellow}opswd: usage with op version $(op --version) is deprecated. Upgrade to CLI 2 and reload zsh.
  33. For instructions, see https://developer.1password.com/docs/cli/upgrade.%f"}
  34. # opswd puts the password of the named service into the clipboard. If there's a
  35. # one time password, it will be copied into the clipboard after 10 seconds. The
  36. # clipboard is cleared after another 20 seconds.
  37. function opswd() {
  38. if [[ $# -lt 1 ]]; then
  39. echo "Usage: opswd <service>"
  40. return 1
  41. fi
  42. local service=$1
  43. # If not logged in, print error and return
  44. op list users > /dev/null || return
  45. local password
  46. # Copy the password to the clipboard
  47. if ! password=$(op get item "$service" --fields password 2>/dev/null); then
  48. echo "error: could not obtain password for $service"
  49. return 1
  50. fi
  51. echo -n "$password" | clipcopy
  52. echo "✔ password for $service copied to clipboard"
  53. # If there's a one time password, copy it to the clipboard after 5 seconds
  54. local totp
  55. if totp=$(op get totp "$service" 2>/dev/null) && [[ -n "$totp" ]]; then
  56. sleep 10 && echo -n "$totp" | clipcopy
  57. echo "✔ TOTP for $service copied to clipboard"
  58. fi
  59. (sleep 20 && clipcopy </dev/null 2>/dev/null) &!
  60. }
  61. }
  62. opswd "$@"