BASH function with tmux send-keys

前端 未结 1 863
梦谈多话
梦谈多话 2021-02-10 09:16

I\'m having problems putting \"send-keys\" into a bash function. Here\'s a minimal example:

function keys {
  tmux send-keys -t work:1 $*
}

tmux new-session -d          


        
1条回答
  •  被撕碎了的回忆
    2021-02-10 09:45

    You should use "$@" (the quotes are important) instead of $* in your shell function; it will preserve the positional parameters exactly as they are supplied in the function invocation.

    function keys {
      tmux send-keys -t work:1 "$@"
    }
    

    With "$@", the final command will get the four original arguments:

    tmux send-keys -t work:1 'pwd' 'c-m' 'ls -latr' 'c-m'
    

    Instead of the five from unquoted $*:

    tmux send-keys -t work:1 pwd c-m ls -latr c-m
    

    Or the one from "$*":

    tmux send-keys -t work:1 'pwd c-m ls -latr c-m'
    

    When unquoted, $* and $@ are effectively identical, but they are significantly different when unsed in double quotes.

    • $* and $@ are like $1 $2 $3 …

      The resulting values are subject to word splitting and filename expansion (a.k.a. globbing), so you usually do not want to use these (or any other parameter expansions) without double quotes.

      The additional word splitting is why your "ls -ltr" (one argument to key) becomes ls -ltr (two arguments to tmux send-keys).

    • "$*" is like "$1 $2 $3…"

      All the positional parameter values are joined into a single “word” (string) that is protected from further word splitting and globbing.

      The character that is put between each positional parameter value is actually the first character from IFS; this is usually a plain space.

    • "$@" is like "$1" "$2" "$3" …

      Each positional parameter is expanded into a separate word and they are protected from further word splitting and globbing.

    0 讨论(0)
提交回复
热议问题