4

In the zsh shell, I can write something into the command line history like so:

#!/bin/zsh
cmd="cd /special/dir" 
print -s $cmd"        # save command in history for reuse

How may I do that in the fish shell?

2
  • There's print -s in ksh93 and zsh, but though bash has a print example loadable builtin (often not installed let alone enabled by default), it just ignores the -s option. Commented Jan 30, 2021 at 7:00
  • @StéphaneChazelas Thank you, i have edited this question. But do you have a way to save command to history in a fish script ?
    – bigxu
    Commented Jan 30, 2021 at 16:16

1 Answer 1

4

AFAICT, only the read builtin and the shell command line reader can add entry to the history, but only when stdin is a tty device, so that's not easily scriptable.

But you could add the entry by hand with something like:

function add_history_entry
  begin
    flock 1
    and echo -- '- cmd:' (
      string replace -- \n \\n (string join ' ' $argv) | string replace \\ \\\\
    )
    and date +'  when: %s'
  end >> $__fish_user_data_dir/fish_history
  and history merge
end

And then:

add_history_entry 'cd /special/dir'

That works for me with fish 3.1.2 here, but note that fish is a bit of a moving target with API changing often in incompatible ways between one version and the next. That __fish_user_data_dir and the format of the history file are not documented, so they might go away/change in a future version. The above also assumes the $fish_history variable is not set to anything other than fish.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .