0

I'm trying to script a small utility to more easily start my day with a custom tmux window. My variable doesn't seem to be evaluated before tmux sends it's keys, however:

#!/bin/bash
MY_WORKSPACE=/users/me/someproject
tmux send-keys 'cd ${MY_WORKSPACE}' 'C-m'

is erring out on a cd ${MY_WORKSPACE} error because MY_WORKSPACE hasn't been replaced with the variable contents.

1

Put it in double quotes: "cd $MY_WORKSPACE"...

  • This answer tells what to do but not why to do. Additionally the code is poor, it will fail for some possible values of $MY_WORKSPACE (see my answer). I'm not voting down only because your answer happens to work with the value in question. – Kamil Maciorowski Dec 3 at 21:37
  • It works well enough, don't confuse a simple question with reams of explanation and pedantry. – Nicholas Marriott Dec 4 at 9:22
  • Fair enough. Your attitude doesn't really correspond with the gist of Stack Exchange though. – Kamil Maciorowski Dec 4 at 10:02
1

MY_WORKSPACE is defined in the script but (most likely) not in the shell that receives the keys you send via tmux send-keys. The variable is single-quoted in the script, so it's not expanded. The shell in tmux gets cd ${MY_WORKSPACE} literally, as if you typed it. Undefined variable gets expanded to nothing.

You need to double-quote the string in the script, so the variable is expanded there. Its content will be typed into the shell in tmux. Then it will be interpreted.

In your case the variable expands to /users/me/someproject. This string contains no spaces nor other troublesome characters. The solution from this other answer will work with this string. It's like:

# flawed
tmux send-keys "cd $MY_WORKSPACE" 'C-m'

In general this code is poor. You should at least single-quote the expanded content:

#!/bin/bash
my_workspace='/users/me/some project with spaces'
# still somewhat flawed in general
tmux send-keys "cd '$my_workspace'" 'C-m'

(I used lowercase name for the variable because it's a good practice.) The target shell will receive the expanded variable content in single-quotes. This will prevent word splitting, globbing and further expansion of $ (if any) etc. Still literal single-quote(s) in the variable content may break the command and even inject arbitrary commands. There are ways to avoid this. Bash itself provides a convenient solution:

#!/bin/bash
my_workspace="with spaces \$foo['\" and various characters"
# safe
tmux send-keys "cd ${my_workspace@Q}" 'C-m'

${my_workspace@Q} expands to a string that recreates the original string as one word upon being interpreted. You don't even need additional single-quotes, they will be added during variable expansion.

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.