0

I can't get path from variable in bash. How do it correct? For example:

my@PC:~$ a="~/.bashrc"
my@PC:~$ cat $a
cat: ~/.bashrc: No such file or directory

didn't work, but

cat .bashrc

and

cat ".bashrc"

Works well.


Here is right answer from fedorqui

cat $(eval echo $a)
Stepan Loginov
  • 1,667
  • 4
  • 22
  • 49

1 Answers1

3

The reason for the issue is that the tilde is expanded to the home directory by the shell. When you store it in a variable, the tilde is not expanded and cat looks for a file .bashrc in the folder ~ (rather than your home directory)

There are two ways around the issue: the proposed eval, and using $HOME:

a="$HOME/.bashrc"
SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • 3
    You could also use `a=~/".bashrc"` or even `a=~/.bashrc` -- as long as the `~` is outside the quotes it'll be expanded (unlike `$variable`, which is expanded even inside double-quotes). – Gordon Davisson Jul 25 '13 at 16:13