1

Consider the following Bash script:

function dosomething {
    local fname="~/.bash_profile"
    if [[ -f "$fname" ]]; then
        echo "proceeding"
    else
        echo "skipping"
    fi
}

dosomething

I always get "skipped" although I know that ~/.bash_profile exists. Why?

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
Nikolay Dutchuk
  • 643
  • 2
  • 6
  • 11

1 Answers1

10

~ is only expanded by the shell if it's unquoted. When it's quoted it's a literal tilde symbol.

local fname=~/.bash_profile
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
  • Thanks! I'll be using `'local fname="/Users/$(whoami)/.bash_profile"` instead. – Nikolay Dutchuk Sep 26 '18 at 14:20
  • 7
    That seems like way more work than simply unquoting the `~`. Also, it technically makes an assumption about where the user's home directory is that doesn't have to be true. Use `$HOME` if you don't want to use `~`. – chepner Sep 26 '18 at 14:24