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.

5
  • 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) ~. Commented Sep 19, 2023 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. Commented Sep 19, 2023 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. Commented Sep 19, 2023 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. Commented Sep 20, 2023 at 0:51
  • @Kaz and that expectation isn't valid - it arises from a misunderstanding which is addressed in the dupe. Commented Sep 20, 2023 at 1:12

1 Answer 1

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
  • 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. Commented Sep 19, 2023 at 14:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.