How to prevent the following to run `~/.bashrc` before `echo test`?

`~/.ssh/authorized_keys`:
```
command="echo test" ssh-ed25519 CENSORED user@host
```
Jun 2, 10:53pm

The issue is that your ~/.bashrc file is being sourced before the echo test command runs when the SSH session starts. This happens because, by default, SSH sessions that execute a command (via command="..." in authorized_keys) still initialize a login shell, which sources ~/.bashrc.


Solutions

1. Use bash -c with --noprofile and --norc

Modify the command in your ~/.ssh/authorized_keys to explicitly skip sourcing ~/.bashrc and ~/.bash_profile:

bash
command="bash --noprofile --norc -c 'echo test'" ssh-ed25519 CENSORED user@host
  • --noprofile: Skips reading ~/.bash_profile, ~/.bash_login, and ~/.profile.
  • --norc: Skips reading ~/.bashrc.

2. Use /bin/sh Instead of bash

If you don’t need Bash features, use /bin/sh (which typically doesn’t source ~/.bashrc):

bash
command="sh -c 'echo test'" ssh-ed25519 CENSORED user@host

3. Set BASH_ENV to /dev/null

If you must use Bash, you can force it to skip ~/.bashrc by setting BASH_ENV to /dev/null:

bash
command="BASH_ENV=/dev/null bash -c 'echo test'" ssh-ed25519 CENSORED user@host

4. Use env to Clear Environment Variables

If the issue is caused by environment variables set in ~/.bashrc, you can clear them:

bash
command="env -i bash --noprofile --norc -c 'echo test'" ssh-ed25519 CENSORED user@host
  • env -i: Starts with an empty environment.

Why This Happens

  • When SSH runs a command via authorized_keys, it spawns a non-interactive, non-login shell by default.
  • However, if the user’s shell is Bash, it may still source ~/.bashrc (depending on the BASH_ENV variable or system configuration).
  • The solutions above explicitly prevent Bash from reading its configuration files.
Jun 2, 10:53pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more