Skip to content

// Engineering Log

Secrets and Zero Trust: Part 3 — Bitwarden CLI on Linux: bw, session and secure operation

Published on 2026-11-20 · Author:

// Fast route

This article belongs to the topic Servers and infrastructure.

Bitwarden CLI (bw) — the official Bitwarden command-line client. It lets you search, read, create, modify, and delete items, and work with organizations and collections. With it, secrets from the vault can be injected into scripts and admin commands instead of keeping them in .env, shell history, or notes. bw works with both Bitwarden cloud and a self-hosted Vaultwarden server. Below is how to install bw on Linux, connect it to Vaultwarden, and use it so that secrets do not end up on disk, in logs, or in the process list. Information is verified against the Bitwarden documentation and the CLI source for version 2026.10.0.

Installation

There are three ways.

npm. Node.js 22 or newer and npm 10 or newer are required:

bash
node --version    # v22.x or higher
npm install -g @bitwarden/cli
bw --version

The documentation warns: on Linux installing via npm may require build-essential (sudo apt install build-essential) or the equivalent in your distribution. On arm64 (for example, on Raspberry Pi) the documentation recommends npm: prebuilt binaries are released only for x64.

snap:

bash
sudo snap install bw

Native binary for Linux x64 works without Node.js:

bash
curl -fsSL -o bw.zip 'https://bitwarden.com/download/?app=cli&platform=linux'
unzip bw.zip && chmod +x bw && sudo mv bw /usr/local/bin/

For GitHub builds SHA-256 checksum files are published; verify the archive checksum before installation: take the checksum file from the release page on GitHub (check the exact filename there) and verify with sha256sum -c. There are two variants there: regular and OSS. The OSS build lacks features under closed licenses, for example device approval commands; either is sufficient to work with Vaultwarden.

Connecting to Vaultwarden

By default bw connects to Bitwarden cloud. For a private server set the address before login:

bash
bw config server https://vault.example.ru
bw config server          # shows current address when called without an argument

If the server presents a self-signed certificate or a certificate from your internal CA, specify a Node.js file with the root certificate:

bash
export NODE_EXTRA_CA_CERTS="$HOME/.config/bw/example-ca.pem"

Do not disable certificate verification: the CLI sends the server a hash of the master password and receives access tokens. How to deploy your server behind a reverse proxy is described in the Vaultwarden section.

Login and unlock are separate steps

The CLI has three states, shown by bw status:

bash
bw status | jq -r .status
# unauthenticated — not logged in
# locked          — logged in, vault locked
# unlocked        — vault unlocked

Login (bw login) associates the CLI with an account: the server authenticates you, issues tokens, and the CLI downloads the encrypted vault. Unlock (bw unlock) decrypts the vault on your machine with the master password and creates a session key. Login is done once; unlocking is done for each working session.

bash
bw login you@example.ru     # will ask for master password and, if enabled, second factor
bw unlock                   # will ask for master password and output a session key

Logging in with email and password creates a session key immediately. When logging in by API key or via SSO, bw unlock is then mandatory: the data can only be decrypted with the master password. The commands config, encode, generate, update and status work without unlocking.

Two-step authentication in the CLI

The CLI supports three second-factor methods: authenticator app (TOTP), email code, and YubiKey OTP. The method number is passed in --method:

Method--method
Authenticator (TOTP)0
Email1
YubiKey OTP3
bash
bw login you@example.ru --method 0 --code 123456

FIDO2 WebAuthn and Duo are not supported in the CLI. If the account only has those enabled, you can only log in using an API key (see below). Enter the password interactively so it does not end up in shell history; the one-time code passed as a command argument is visible in the process list for the duration of the command.

Session key: BW_SESSION and –raw

bw unlock prints a ready-to-run command export BW_SESSION="…". With the global --raw option it outputs just the key itself without explanations, so it’s convenient to store it immediately in a variable:

bash
export BW_SESSION="$(bw unlock --raw)"

The CLI prompts for the password to stderr, so if stdout is intercepted the prompt “Master password:” remains on the screen and only the key goes into the variable. Instead of an environment variable you can pass the key with the --session <key> option, but then it is visible in the process list.

The session key is valid until bw lock or bw logout and does not carry over automatically to a new terminal window. When done, lock the vault:

bash
bw lock
unset BW_SESSION

bw lock locks the vault and clears saved state; after it the session key no longer opens data.

Password not as a command-line argument

bw unlock accepts the password as a positional argument: bw unlock <password>. Don’t do that:

  • arguments of any process are visible to all system users in ps aux and /proc/<pid>/cmdline while the process runs (unless /proc is mounted with hidepid);
  • the command with the password goes into shell history (~/.bash_history, ~/.zsh_history);
  • it can also go to the audit log if auditd is enabled on the server with execve logging.

There are two safe options for non-interactive unlocking.

--passwordenv <name> — the CLI reads the password from the environment variable with the given name. The name is arbitrary; BW_PASSWORD in the documentation is only an example. Process environment variables in /proc/<pid>/environ can be read only by the process owner and root, not by all users:

bash
# bash; in zsh: read -rs '?Master password: ' BW_PW
read -rs -p 'Master password: ' BW_PW; echo
BW_SESSION="$(BW_PW="$BW_PW" bw unlock --passwordenv BW_PW --raw)"
export BW_SESSION
unset BW_PW

The assignment BW_PW="$BW_PW" bw … passes the variable only to that process without exporting it to the shell.

--passwordfile <file> — the CLI reads the password from the first line of a file. The documentation advises restricting access to such a file; the CLI does not check file permissions. Create the file with the needed permissions immediately rather than changing them afterward:

bash
mkdir -p -m 700 ~/.config/bw
( umask 077; read -rs -p 'Master password: ' P; printf '%s\n' "$P" > ~/.config/bw/master ); unset P; echo
bw unlock --passwordfile ~/.config/bw/master --raw

A master password in a file on disk is the master password in plain text: anyone who gets a disk copy or a backup of the home directory will find it. Use this option only on a server where automatic unlocking is unavoidable, and account for it in your threat model. How to remove the password from disk and unlock the vault by touching a hardware key is described in the FIDO2 unlock section.

Where to store the session key

The session key together with the local copy of the vault grants access to all items, so treat it like a password. To avoid unlocking the vault in every new terminal, you can place the key in $XDG_RUNTIME_DIR. On systemd systems this is /run/user/<uid> on tmpfs with permissions 0700: it’s stored in memory, accessible only to you, and cleared when all sessions end (unless loginctl enable-linger is enabled for the user) or on reboot.

bash
# unlock and save the key
umask 077
( umask 077; bw unlock --raw > "$XDG_RUNTIME_DIR/bw-session" )   # if unlock failed, delete the empty file

# in ~/.bashrc: pick up the key in new shells
[ -r "$XDG_RUNTIME_DIR/bw-session" ] && export BW_SESSION="$(cat "$XDG_RUNTIME_DIR/bw-session")"

# finish work
bw lock; rm -f "$XDG_RUNTIME_DIR/bw-session"; unset BW_SESSION

What not to do:

  • write the session key into ~/.bashrc, ~/.profile, .env or any other file on disk;
  • print it to a script log: set -x in bash prints expanded commands with argument values (for example, export VAR=value), so tracing is disabled around secret operations (set +x);
  • paste it into chats, tickets, CI jobs;
  • keep the vault unlocked on a shared server where others or services run under your account.

Remember that any process started by your user can read both $XDG_RUNTIME_DIR and the environment variables of your processes. Tmpfs protects against disk theft and other users, but not against a malicious program in your own session.

Reading secrets

bw get returns one object by ID or by search string:

bash
bw get password db.example.ru        # password only
bw get username db.example.ru
bw get totp db.example.ru            # current TOTP code
bw get notes deploy-key
bw get item db.example.ru | jq .     # full item in JSON

If several items match the string, the CLI returns the error “More than one result was found” and prints their IDs. Find the correct one with bw list and then reference it by ID:

bash
bw list items --search db | jq -r '.[] | [.id, .name, .login.username] | @tsv'
bw get password 0f4c9a2e-1b7d-4c8e-9a3f-5d6e7f8a9b0c

Filters --folderid, --collectionid, --organizationid, --url are ORed with each other, and ANDed with --search. Custom field values of an item are extracted via jq:

bash
bw get item 0f4c9a2e-1b7d-4c8e-9a3f-5d6e7f8a9b0c \
  | jq -r '.fields[]? | select(.name == "api_token") | .value'

You don’t have to show a secret on the screen to use it. Pass it directly to a command via an environment variable or standard input:

bash
# environment variable only for one process
PGPASSWORD="$(bw get password db.example.ru)" psql -h db.example.ru -U app appdb

# standard input
bw get password registry.example.ru | docker login registry.example.ru -u deploy --password-stdin

If you changed an item in another client, run bw sync: this command only downloads the vault from the server. Changes made in the CLI (create, edit, delete) are sent to the server immediately. The time of the last sync is shown by bw sync --last.

Creating, editing and deleting items

bw create and bw edit accept JSON in base64. The flow is: take a template, fill it using jq, encode with bw encode, pass to bw create. Do not put the password in the jq filter text: it will end up in process arguments and history. It’s safer to generate the password into a variable and pass it to jq through the environment (env.PW):

bash
PW="$(bw generate -ulns --length 32)"
bw get template item | PW="$PW" jq '
    .type = 1
  | .name = "db.example.ru"
  | .notes = null
  | .login = {
      username: "app",
      password: env.PW,
      uris: [{match: null, uri: "https://db.example.ru"}]
    }' \
  | bw encode | bw create item | jq -r .id
unset PW

Item types: 1 — login, 2 — secure note, 3 — card, 4 — identity, 5 — SSH key.

Edit replaces the item completely, so fetch the current version, change the needed field and send it back:

bash
ID=0f4c9a2e-1b7d-4c8e-9a3f-5d6e7f8a9b0c
NEW="$(bw generate -ulns --length 32)"
bw get item "$ID" | NEW="$NEW" jq '.login.password = env.NEW' | bw encode | bw edit item "$ID"
unset NEW

Deleting by default moves the item to Trash, from where it can be restored. In Bitwarden cloud items are kept in Trash for 30 days; in Vaultwarden the period is set by TRASH_AUTO_DELETE_DAYS (by default items are not auto-deleted). With --permanent the item is deleted irreversibly:

bash
bw delete item "$ID"
bw list items --trash | jq -r '.[] | [.id, .name] | @tsv'
bw restore item "$ID"

Storing an SSH key

There is no ready template for type 5 in the documentation list (item.sshKey is not in the templates). JSON is built from the item template and an sshKey object with three fields: privateKey, publicKey and keyFingerprint. In the client sources all three are marked required:

bash
KEY=~/.ssh/id_ed25519
bw get template item | jq \
    --rawfile priv "$KEY" \
    --rawfile pub "$KEY.pub" \
    --arg fp "$(ssh-keygen -lf "$KEY.pub" | awk '{print $2}')" '
    .type = 5
  | .name = "ssh: deploy@example.ru"
  | .login = null
  | .notes = null
  | .sshKey = {privateKey: $priv, publicKey: ($pub | rtrimstr("\n")), keyFingerprint: $fp}' \
  | bw encode | bw create item | jq -r .id

The private key is read by jq from a file (--rawfile), not from an argument; the fingerprint is public and can be passed via --arg. Support for this type depends on server version, so first create a test item and open it in the Vaultwarden web UI. The built-in SSH agent that supplies such keys to the ssh program is available in the Bitwarden desktop app.

Login by API key

A personal API key (client_id and client_secret) is obtained in the web UI under account security settings. It is needed if the account has a second factor that the CLI does not support, and for automation where you cannot respond to a code prompt:

bash
export BW_CLIENTID='<client_id>'
export BW_CLIENTSECRET='<client_secret>'
bw login --apikey
# Set BW_PW the same way as in the --passwordenv section
bw unlock --passwordenv BW_PW --raw

Login by API key is intended for cases where entering the second-factor code is impossible, so do not store client_secret and the master password together unless necessary. The documentation says plainly: the API key does not replace the master password. It only logs in, and reading data still requires bw unlock with the master password. Leakage of the API key without the master password does not reveal vault contents, but it does allow logging in as you and downloading encrypted data, so store the key as carefully as a password and rotate it if you suspect a leak.

Organizations, collections and permissions

Team secrets are stored in an organization and distributed across collections. In the CLI:

bash
bw list organizations | jq -r '.[] | [.id, .name] | @tsv'
bw list collections | jq -r '.[] | [.id, .name] | @tsv'
bw list items --collectionid <collection_id>
# move a personal item into an organization and a collection
echo '["<collection_id>"]' | bw encode | bw move "$ID" <organization_id>

Member roles in an organization: Owner, Admin, User; custom roles exist in Bitwarden only on the Enterprise plan. At the collection level Bitwarden documents permissions “View items”, “View items, hidden passwords”, “Edit items”, “Edit items, hidden passwords” and “Manage collection”. Hidden passwords are not fully protective: autofill still works, and Bitwarden recommends treating such a password as delivered to the user. Which of these levels are implemented in your Vaultwarden version, check in its UI. For automation create a separate user with access only to the needed collection rather than using your account with access to everything.

Wrapper script

A script that fetches a secret from the vault and passes it to a single command without writing the secret to disk or passing it as command-line arguments:

bash
#!/usr/bin/env bash
# with-secret: with-secret <item> <VARIABLE> -- command [args]
set -euo pipefail
set +x

item="$1"; var="$2"; shift 2
[ "${1:-}" = "--" ] && shift

: "${BW_SESSION:?Vault is not unlocked: export BW_SESSION=\"\$(bw unlock --raw)\"}"

value="$(bw get password "$item" --nointeraction)" || {
  echo "Failed to get $item" >&2; exit 1
}

# exec replaces the script with the command: the variable exists only in its environment
export "$var=$value"
unset value BW_SESSION
exec "$@"
bash
with-secret db.example.ru PGPASSWORD -- psql -h db.example.ru -U app appdb

--nointeraction prevents the CLI from prompting for a password mid-script: if the vault is locked the command will exit immediately with “Vault is locked.” The secret value does not go into arguments, output, or history; it remains in the environment of the launched command and can be read by a process of the same user or by root. The script removes the session key BW_SESSION from the environment before launching the command.

If you still must type a command with a secret manually, don’t save it to history. In bash:

bash
export HISTCONTROL=ignoreboth   # lines beginning with a space are not saved
 export MYSQL_PWD='<password>'    # leading space: the command will not be saved
set +o history                  # disable history in the current session
set -o history                  # enable it again

The history option exists only in bash; in zsh lines starting with a space are not saved with setopt HIST_IGNORE_SPACE. The example places the password in the environment rather than the argument: HISTCONTROL hides the command only from history, while the command-line argument remains visible in the process list. But it’s more reliable not to enter secrets on the command line at all. How to avoid leaking secrets to Git is covered in the article “Secure Development: Part 2 — Secrets in Code”.

Common errors

" You are not logged in." — not logged in or logged in with a different BITWARDENCLI_APPDATA_DIR. Check bw status, and if needed bw config server and bw login.

“Vault is locked.” — the vault is locked and the CLI was run with --nointeraction; without that option it would prompt for the master password. Run bw unlock --raw and export BW_SESSION.

Invalid or expired BW_SESSION. After bw lock, bw logout or re-unlock the old key is invalid: commands report the vault is locked or cannot decrypt data. Unlock again and update the saved key in $XDG_RUNTIME_DIR.

“More than one result was found.” — the search string matches multiple items. Use the ID from bw list items --search.

“Not found.” — the item does not exist or the CLI does not yet see it: it was created in another client after the last sync. Run bw sync.

Certificate error on bw login — the server uses an internal CA certificate. Specify NODE_EXTRA_CA_CERTS; do not disable verification.

Warning “Warning: Provided passwordenv … is not set” — the variable name passed to --passwordenv is empty or was not passed to the process; in that case the CLI will prompt for a password, and with --nointeraction you’ll get “Master password is required. Try again in interactive mode or provide a password file or environment variable.” Pass the variable name, not its value: --passwordenv BW_PW, not --passwordenv "$BW_PW".

For debugging the server connection the CLI emits verbose logs when BITWARDENCLI_DEBUG=true. Before sending such a log to someone, check that it contains no tokens.

// Similar task

If you are dealing with something similar

This article belongs to one of the main working topics. You can keep reading on the topic, go to the homepage to understand what I do, or open the service pages directly.

Article topic

Servers and infrastructure

VPS, Linux, web stack, migrations, hosting, databases, and core operations.

Typical tasks behind this topic

  • Move a site or service to a new server
  • Set up Linux, Nginx, databases, and backups
  • Figure out why the system behaves unstably

// Next step

If you need help with this topic, not just another article, it is better to go straight to the service page. The homepage and topic collection stay available as secondary routes.

Open services

// Contact

Need help?

Get in touch with me and I'll help solve the problem

I reply within one business day (03:00-13:00 GMT)

Or leave a request here:

Confirm that you are not a bot.

Write and get a quick reply