0

I have the following variable that shows where I should write my report to REPORT="ZFS(~/Q4Y22/report/q4y22.md)"

I have used sedto extract the path and dirname command to get the ~/Q4Y22/report/dir name which I assign to reportdir variable.

However when I run the following test, instead of the Q4Y22 dir being created in my home dir, it literally creates the following directory hierachy ~/Q4Y22/report inside my home for example farai/~/Q4Y22/report instead of farai/Q4Y22/report

if [ -d $reportdir ]
then
    echo "dir exists, keep moving"   
else
    mkdir -p $reportdir
fi

How do I get around this, I tried using sed to remove the tilde from the path but i was wondering if there is a more clever way

Fnechz
  • 151
  • 8

1 Answers1

0

My try on this:

#!/bin/bash
REPORT="~/Q4Y22/report/q4y22.md"
reportdir=$(dirname "${REPORT/'~'/$HOME}")
if [ -d "$reportdir" ]
then
    echo "dir exists, keep moving"   
else
    mkdir -p "$reportdir"
fi

This is a bit fragile since you could have ~ in the filename, though, but you could improve this script to replace only the first char if it's a tilde.

Niloct
  • 9,491
  • 3
  • 44
  • 57
  • `realpath` doesn't expand `~`. – Barmar Dec 26 '22 at 22:19
  • They said that they're getting `reportdir` by extracting it from the `REPORT` variable. – Barmar Dec 26 '22 at 22:20
  • 1
    The tilde is being expanded by the shell before passing it to realpath. Try `realpath '~'` – Barmar Dec 26 '22 at 22:25
  • Notice that it left the literal `~` in the output. – Barmar Dec 26 '22 at 22:49
  • 1
    It's resolving it as a literal name relative to the current directory, it's not converting it to `$HOME`. – Barmar Dec 26 '22 at 23:04
  • You were right on your comments regarding what I wrote first, thanks. Take a look at the edited answer. – Niloct Dec 26 '22 at 23:19
  • 1
    Instead of manually replacing the tilde, why don't you set set `REPORT=~/Q4Y22/report/q4y22.md` (without quotes, so that ~ gets expanded by bash), or `REPORT="$HOME/Q4Y22/report/q4y22.md"`, which also would do the same? – user1934428 Dec 27 '22 at 08:50
  • @user1934428 if he can modify the variable definition, that's a better option indeed (my first answer did something similar). – Niloct Dec 27 '22 at 21:05