How to expand tilde in bash script

When I was working on a recent bash script, I was irritated when I wasn’t getting output to my desktop. After a while, I figured out that quoted tildes are not automatically expanded.

From that link:

If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix.

The “quoted” part being the key phrase. Thus, if your tilde is in quotes, it will not be expanded. This issue is demonstrated by the following:

?  ~ path="~/Desktop"
?  ~ cd "$path"
cd: no such file or directory: ~/Desktop

Never fear though, there is an easy solution for this: parameter expansion. ?

?  ~ path="~/Desktop"
?  ~ path=${path/\~/$HOME}
?  ~ cd "$path"
?  Desktop

What we’re doing here is basically a find and replace. We take in path, search for ~, and replace it with $HOME. This gives us a valid path like /Users/username/Desktop which we can then use in various commands.

Now, before you actually implement this, maybe consider whether you need to. In my case, the issue was that I was quoting an argument to my script. Instead of using parameter expansion to expand the tilde, I could’ve simply unquoted the path as it was passed to the script.

But, you know, lessons learned. ¯_(?)_/¯

One response to “How to expand tilde in bash script”

  1. use path=${path#\~/$HOME} so you only expand ~ at the beginning of the path

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.