4
\$\begingroup\$

After inspecting fzf/shell/key-bindings.bash I came up with the following, to be put in my ~/.bashrc:

fzf_get_env_vars() {
 local cmd opts selected
 cmd='command env | command sed "s/=.*//;s/^/$/"'
 opts="--height ${FZF_TMUX_HEIGHT:-40%} --bind=ctrl-z:ignore --reverse $FZF_DEFAULT_OPTS $FZF_CTRL_T_OPTS -m"
 selected="$(eval "$cmd" \
 | FZF_DEFAULT_OPTS="$opts" $(__fzfcmd) "$@" \
 | while read -r item; do
 printf '%s ' "$item"
 done
 )"
 READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$selected${READLINE_LINE:$READLINE_POINT}"
 READLINE_POINT=$(( READLINE_POINT + ${#selected} ))
}
# I'm a vi-mode user, so no need for emacs mapping
bind -m vi-command -x '"\ee": fzf_get_env_vars'
bind -m vi-insert -x '"\ee": fzf_get_env_vars'

Major changes I've applied to what I've seen in the linked files are

  • I've not split the function that calls fzf and retrieves the user-selected values from the function reassinging READLINE_LINE and READLINE_POINT;
  • given the inputs are variable names, I think not escaping (i.e. '%s ' instead of '%q ') is safe,
  • which in turns also allows me to prepend $ (via the second s command in the sed script) without it being escaped.

ShellCheck detects no issues with the code.

asked Nov 4, 2022 at 18:44
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It's worth avoiding eval if possible.

Given your code, without the eval I came up with this:

fzf_sed_env_vars_cmd() {
 builtin command env |
 builtin command awk -F'=' '{printf "$%s\n", 1ドル}'
 # builtin command sed "s/=.*//;s/^/$/"'
}
fzf_get_env_vars() {
 builtin local opts selected
 opts="--height ${FZF_TMUX_HEIGHT:-40%} --bind=ctrl-z:ignore --reverse $FZF_DEFAULT_OPTS $FZF_CTRL_T_OPTS -m"
 selected="$( ##: Look Mah, No Eval!!! :-)
 fzf_sed_env_vars_cmd |
 FZF_DEFAULT_OPTS="$opts" $(__fzfcmd) "$@" |
 while builtin read -r item; do
 builtin printf '%s ' "$item"
 done
 )"
 READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$selected${READLINE_LINE:$READLINE_POINT}"
 READLINE_POINT=$(( READLINE_POINT + ${#selected} ))
}
# I'm a vi-mode user, so no need for emacs mapping
builtin bind -m vi-command -x '"\ee": fzf_get_env_vars'
builtin bind -m vi-insert -x '"\ee": fzf_get_env_vars'

answered May 27, 2023 at 1:08
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.