I want to create a file and read in function declaration to be able to edit it further.

e() { echo $FUNCNAME }
vim FILE < <(declare -f e )

but that doesn't seem to work and the filename expands to the file descriptor: /proc/10422/fd/63. The process already exited, probably it was one created by vim.

Please suggest a way to name a file and read a command output at once.

  • I don't understand. After this comomand, what should the filename and the file contents be? Is it declare -f e > file that you want? – glenn jackman Nov 12 '20 at 1:47

It's somewhat easy to get a function definition and open it in Vim for editing:

declare -f e l vim -

But there are many shortcomings with that approach. For instance, exiting Vim after editing the file won't really reload the function with the new definition. In fact, the buffer you get by reading it from standard input is an unnamed buffer, so Vim won't really save it with :w or :wq or ZZ, it will prompt for a file to save in that case...

If you want to reload the definition after an edit, you should use a temporary file and have Vim edit that file. Once Vim exits, you can reload the contents of the temporary file.

For example:

edfunc() {
  local funcname=$1
  local tmpfile=$(mktemp -t edfunc-XXXXXXXX.sh)
  trap 'rm -f "$tmpfile"' RETURN
  declare -f "$funcname" >"$tmpfile" || {
    echo "No such function [${funcname}]." >&2
    return 1
  vim "$tmpfile" || return 1
  . "$tmpfile"

And then you can use it with:

$ edfunc e

Once you modify the function definition, edfunc will source it back into the shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.