1

I am a long time bash user, but ran into something I have never seen before (or simply don't remember). I was getting a "No such file or directory" error when trying to redirect output to a log file, something I have done thousands of times but evidently not quite in this manner. Here is a sample output that recreates the problem:

test.sh:

#!/bin/bash
logfile="~/logs/$(date +%Y%m%d_%H%M%S).log"
echo "Test" > ${logfile}

output:

$ ./test.sh
./test.sh: line 3: ~/logs/20220114_025115.log: No such file or directory

I finally isolated the problem to the ~, and the workaround to my problem is to use $HOME or hard-code the full path (boo!), but my question is why does the ~ operator not get expanded to be my home directory? I googled for an answer, but nothing quite matches my question. Thanks in advance.

  • 2
  • So, I see the duplicate article and agree that was the answer I was looking for and my question is a duplicate. My first inclination then would be to remove the duplicate and allow the better question/answers stand, but when I tried delete, it said that was not recommended either. Is the standard approach here to just keep the duplicate but close the question (already closed). Just curious if there is anything more I should be doing as the one who proposed the duplicate question? – DBAYoder Feb 07 '23 at 19:11

1 Answers1

2

Tilde expansion occurs only when the tilde character is unquoted. From the bash manual:

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.

https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html

You can force the expansion by moving the quote to the position after the first slash character. That is, from "~/logs/$(date +%Y%m%d_%H%M%S).log" to ~/"logs/$(date +%Y%m%d_%H%M%S).log".

Haxiel
  • 8,361
  • Thank you much. I totally missed it in the man pages. Searched on ~, not Tilde, and found quite a few references! ;) – DBAYoder Jan 14 '22 at 15:02