0

I do not understand the behaviour of this variable:

SSH_CONFIG_FILE="~/.ssh/config"
echo $SSH_CONFIG_FILE
ls -l $SSH_CONFIG_FILE
ls -l ~/.ssh/config

This is the output:

~/.ssh/config
ls: cannot access '~/.ssh/config': No such file or directory
-rw------- 1 pm domain^users 1229 Sep 19 10:52 /home/pm/.ssh/config

Why does echo work with the $ notation, and ls does not?

I tried surrounding the variable with "", '', ``, {}, [] with no improvement.

Kusalananda
  • 333,661
Pietro
  • 581
  • Note that echo outputs a tilde, not the user's home directory path (as echo ~/.ssh/config would do). If that is what you mean by "works", then you should not be surprised that ls cannot list the file in a sub-directory of a directory called (literally) ~. – Kusalananda Sep 19 '23 at 14:41
  • This question is closed with the wrong duplicate. This is not about quotes. The question contains an example without quotes that behaves unexpectedly. – Kaz Sep 19 '23 at 20:01
  • @Kaz which example? The echo, first ls and second ls all behave exactly as expected - the tilde from the result of a variable expansion isn't expanded, a plain tilde is. And the tilde from the result of the variable expansion is there because it wasn't expanded inside quotes when assigning to the variable. – muru Sep 19 '23 at 23:40
  • @muru Question says, "why does echo work with the $ notation and ls does not?" I.e. why can we echo $SSH_CONFIG_FILE and see ~/.ssh/config as expected but ls $SSH_CONFIG_FILE reports an error? OP expects the unquoted $SSH_CONFIG_FILE in the ls command to be resolved with the tilde. – Kaz Sep 20 '23 at 00:51
  • @Kaz and that expectation isn't valid - it arises from a misunderstanding which is addressed in the dupe. – muru Sep 20 '23 at 01:12

1 Answers1

1

Don't put quotes around tilde ~ if you expect the shell to expand it to your home, so:

SSH_CONFIG_FILE=~/.ssh/config

if you have space(s); do

var=~/'foo bar/file'

With the quotes on tilde, you prevent the shell to expand it to treat literally.

  • 1
    While this is true (if you want the tilde to be expanded to $HOME - never is such a strong word ;) ), it might be worthwile clearing the confusion by explaining why it didn't work in the invocation ls -l $SSH_CONFIG_FILE where the variable was not surrounded by quotes. – AdminBee Sep 19 '23 at 14:30