0

I try to determinate, if a given path points to a file or a directory. I tried this with following code:

#if $mypath is a file
if [[ -f $mypath ]]; then

and

#if mypath is a directory
if [[ -d $mypath ]]; then

Both of these snippets are working fine, when the given path is absolute e.g. /home/user/mydir/... But when the given path starts with a ~, like ~/mydir/... both of these snippets will return true, regardless if the path points to a file, or directory.

Does anybody know, what I'm missing, or if it's even possible?

  • 1
    Unrelated: The variable called PATH is very special. It contains a list of directories where commands may be used. Please use another variable name, preferably lower case. See e.g. Are there naming conventions for variables in shell scripts? – Kusalananda Feb 18 '19 at 19:30
  • 1
    I can't reproduce this in bash 5.0. How do you assign the value to your variable? – Kusalananda Feb 18 '19 at 19:40
  • 1
    In fact, if $mypath contains an actual tilde character, which has not been expanded to a home directory, both should test should fail (unless there's a file or directory with an actual tilde in its name at that path). – Kusalananda Feb 18 '19 at 19:44
  • I fetch them from a config file, which is filtered, by a few simple grep commands. conf=$(cat /path/to/conf | grep -v "#" | grep -ve "^$") – flobue Feb 18 '19 at 19:56
  • What do you mean with both tests should fail? That both won't work correctly, or just return a false? And what do you mean with an actual tilde character? Would they automatically be expanded in some cases? – flobue Feb 18 '19 at 20:04
0

I found the problem.

The problem was, that I was fetching the path from an config file, and thus the path was saved as string. Trough this, the tilde was not expanded, which is the cause for the problem. My workaround was just to manually replace the tilde with $HOME, which will be expanded, even if the path is quoted. So basically:

mypath="${mypath/#\~/$HOME}"
#if $mypath is a file
if [[ -f $mypath ]]; then
| improve this answer | |

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.