Score:0

-f $file_name doesn't work when using ~/file_name but works when using /home/james/file_name

cn flag

This has been driving me nuts. I have a pretty simple script

#!/bin/bash

read -p "Enter changeList.txt file name: " file_name

if  [ -f $file_name ]; then
    echo "Reading File..."
    cat $file_name | grep "Change " | cut -d ' ' -f 2
    echo "Process complete"
else
    echo >&2 "File Note Found."
    exit 1
fi 

echo "Exiting..."
exit 0

I pass it a file ~/changeList.txt, that fails. I pass it /home/james/changeList.txt, and it works. I try

file_name=~/changeList.txt
[ -f $file_name ] && echo "true" || echo "false"

from my terminal and it returns true.
I am using Ubuntu on wsl 2, and I am signed in as james.

hr flag
Related: [Why isn't tilde expansion performed on the input to read?](https://askubuntu.com/questions/1093906/why-isnt-tilde-expansion-performed-on-the-input-to-read)
Score:1
tm flag

Tilde expansion happens before variable expansion. In an assignment, the right hand side value undergoes tilde expansion, so the variable is assigned the full path. See man bash for details.

James Ayres avatar
cn flag
Do you know if there is a way to do tilde expansion from a string coming in or should I just not pass in a tilde?
tm flag
`man bash` mentions `set expand-tilde On` with `read -e`, but I haven't been able to make it work.
au flag
@JamesAyres There are a bunch of options (of varying degrees of complexity and reliability) under the stackoverflow question ["How to manually expand a special variable (ex: ~ tilde) in bash"](https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash).
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.