2

I can run the following two commands for example and get the output locally:

ssh user@remote.ip ls > testhistory.txt  
ssh user@remote.ip "cat .bash_history" > testhistory.txt  

But if I run the following command, the local output is always empty:

ssh user@remote.ip history > testhistory.txt

If I ssh to the remote destination and then run the history command, i get the expected output.

Why does the history command not output results when run inline with ssh but the ls command works normally? What do i need to change to make the history command output results to local file the way I did the ls command without having to cat the .bash_history file?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

3

history is an internal command to bash, so you don't want to run the executable history, you want to run the executable bash. ls works because is an executable on its own, usually at /bin/ls.

Besides that, by default bash disables the history in non-interactive shells, as is the case when you run a remote command.

You can create a shell script in the remote machine to enable it and run history, example:

#!/usr/bin/bash
HISTFILE=~/.bash_history
set -o history
history

Or, if you really want to do all that from the ssh call, you can do:

ssh user@remote.ip 'echo -e "HISTFILE=~/.bash_history\nset -o history\nhistory" | bash'

Note that it also doesn't take into account the HISTTIMEFORMAT variable, if you use it in the remote machine, so plan for that.

References: History command inside bash script

msb
  • 2,654
  • what would a working command look like? ssh user@remote.ip "bash history" > testhistory.txt doesn't work –  Sep 10 '18 at 23:24
  • 1
    ssh with additional non-option arguments passes them to the remote shell (all as one -c) so builtins DO work (try ssh u@h declare -p); noninteractive -> disable history is the only issue. And you don't need the remote shell to run yet another, just ssh u@h 'HISTFILE=~/.bash_history; set -o history; history' -- or even quote only the semicolons: ssh u@h HISTFILE=~/.bash_history';'set -o history';'history but that looks really odd – dave_thompson_085 Sep 11 '18 at 03:17
  • Is there a way to make all variables enabled or find out what's disabled when in non-interactive shell? –  Sep 11 '18 at 19:10