BASH function with tmux send-keys

I have problems sending send-keys to the bash function. Here is a minimal example:

function keys { tmux send-keys -t work:1 $* } tmux new-session -d -s work keys "pwd" cm "ls -latr" cm tmux attach-session -t work 

The key argument here is exactly what I would type on the command line as the tmux send-keys argument. It almost works, but runs through spaces, so I see ls-latr all as one word. But if I put the quotation marks around $* in the function, it just prints the entire argument of the keys in one line (processing cm in the form of alphabetic characters). How can I make it execute the send-keys argument as if I typed it from the command line?

+4
source share
1 answer

You should use " $@ " (quotation marks are important) instead of $* in your shell function; it will save the positional parameters exactly as they will be included in the function call.

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

With " $@ " final command will receive four source arguments:

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

Instead of five of the unquoted $* :

 tmux send-keys -t work:1 pwd cm ls -latr cm 

Or one of the "$*" :

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

If incorrect, $* and $@ virtually identical, but they are significantly different if not in double quotes.

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

    The resulting values ​​are subject to word splitting and file extension (aka globbing), so you usually do not want to use these (or any other parameter extensions) without double quotes.

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

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

    All values ​​of positional parameters are combined into one word (string), which is protected from further splitting and globalization of words.

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

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

    Each positional parameter is expanded into a separate word, and they are protected from further splitting and globalization of words.

+13
source

All Articles