Search code examples
bashtilde-expansion

Unable to test whether a file exists in Bash


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?


Solution

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

    local fname=~/.bash_profile