\$\begingroup\$
\$\endgroup\$
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 reassingingREADLINE_LINE
andREADLINE_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 seconds
command in thesed
script) without it being escaped.
ShellCheck detects no issues with the code.
asked Nov 4, 2022 at 18:44
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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
lang-bash