0

I'm trying to get the filename of the newest file in a directory and store it in a variable. The files in the directory end with *.db.backup. When I try to run the command without storing the result in a variable it is correct, but when I try to store it in a variable for later use and echo the '.' are replaced by spaces. Any ideas as to what I am missing here?

ls -1t | grep "db.backup" | head -1
#Output:
2022-01-11-001712-gravity.db.backup


filename=$(ls -1t | grep "db.backup" | head -1)
echo $filename
#Output:
2022-01-11-001712-gravity db backup
  • It worked here with linux+bash 5.0 – Incrivel Monstro Verde Jan 11 '22 at 18:42
  • # Ran the following: ( set -o posix ; set ) | grep name # Which gives: name=2022-01-11-001712-gravity.db.backup My version is 5.1.4 – bigpancakestack Jan 11 '22 at 18:47
  • 1
    Have you changed `IFS`? Both that and unquoted variables are asking for trouble (see ["I just assigned a variable, but `echo $variable` shows something else"](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else)), and doing both at once is nearly guaranteed to do something weird like this. – Gordon Davisson Jan 11 '22 at 18:53
  • Yes, that seemed to be the issue here! Changed it now, works fine. Thank you, @GordonDavisson! – bigpancakestack Jan 11 '22 at 19:07
  • 2
    It is a good practice to always put quotation marks around variable calls, like `echo "$filename"`, even better `echo "${filename}"`. Otherwise, the content of the variable maybe interpreted in a way you don't expect. – Ina Jan 11 '22 at 19:40

0 Answers0