Clear last bash command from history from executing bash script

Viewed 72

I have a bash script, which uses expect package to ssh into a remote server.

My script looks like this:

#!/bin/bash

while getopts "p:" option; do
   case "${option}" in
      p) PASSWORD=${OPTARG};;
   esac
done

/usr/bin/expect -c "

spawn ssh my.login.server.com
expect {
   \"Password*\" { 
     send \"$PASSWORD\r\" 
   }
 }
interact
"

I run it like ./login.sh -p <my-confidential-password>

Now once you run it and log in successfully and exit from the remote server, I can hit up-arrow-key from the keyboard and can still see my command with password in the terminal. Or I simply run history it shows up. Once I exit the terminal, then it also appears in bash_history.

I need something within my script that could clear it from history and leave no trace of the command I ran (or password) anywhere.

I have tried:

  • Clearing it using history -c && history -r, this doesn't work as the script creates its own session.
  • Also, echo $HISTCMD returns 1 within script, hence I cannot clear using history -d <tag>.

P.S. I am using macOS

1 Answers

You could disable command history for a command:

set +o history
echo "$PASSWORD"
set -o history

Or, if your HISTCONTROL Bash variable includes ignorespace, you can indent the command with a space and it won't be added to the history:

$ HISTCONTROL=ignorespace
$ echo "Hi"
Hi
$  echo "Invisible"  # Extra leading space!
Invisible
$ history | tail -n2
    7  echo "Hi"
    8  history | tail -n2

Notice that this isn't secure, either: the password would still be visible in any place showing running processes (such as top and friends). Consider reading it from a file with 400 permissions, or use something like pass.

You could also wrap the call into a helper function that prompts for the password, so the call containing the password wouldn't make it into command history:

runwithpw() {
    IFS= read -rp 'Password: ' pass
    ./login.sh -p "$pass"
}
Related