ScrawnySquirrel ScrawnySquirrel - 1 month ago 18
Linux Question

Why can't bash find files when the location is stored in a variable?

I am trying to write the

file if it does not exist in the postgres user's home directory.

Currently I have

local PASS="~postgres/.pgpass"
echo "*:*:*:*:$PWD" >> $PASS

and it fails with
~postgres/.pgpass: No such file or directory

However, not using the variable works.

echo "*:*:*:*:$PWD" >> ~postgres/.pgpass

What's the difference between the two? How can I store the file in a variable and get it work?


A couple of things,

Bash: ~ is a shell expansion.

~ doesn't extually exist as a path.

ls $f 

will error

ls: cannot access '~/': No such file or directory

Instead, use the variable $HOME

Typo or wrong file: ~postgres/.pgpass

This is a typo, you want ~/.pgpass, or $HOME/.pgpass on Unix. From the pg docs on the Password File

The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).