0

Summary:

I am trying to have a script that allows easy one-touch access to files that are generated by the crontab.
The hourly generated files go by the path as: /home/mouse/20210126/0900.
Of course as the date and time changes, the path will change like so:

/home/mouse/20210126/1000
/home/mouse/20210126/1100
/home/mouse/20210127/1000
/home/mouse/20210128/1300

I tried using an alias, but once .bashrc is loaded, it only takes the present date/time, which means that I cannot "refresh" the date and time.

So by using a script, I could update the date and time like so:

currentdate=$(date +%Y%m%d)
currenttime=$(date -d '1 hour ago' "+%H00")
collect=cd /home/mouse/$currentdate/$currenttime

echo $currentdate
echo $currenttime
$collect

However, I realized that the cd script is not working because, from my understanding, it works on a subshell and once the script has finished executing, it does not affect the main shell.

I tried source / . but I get /home/mouse/20210126/1000 is a directory.

What is the recommended action I should take to resolve this?

Derpy
  • 1
  • 1
  • 1
    Your command isn't assigning to a variable named `collect` at all. `foo=var somecommand` immediately runs `somecommand` with `foo` temporarily defined as a variable having the value `var`, but _only for the duration of `somecommand`'s execution_. It doesn't in any way set `foo` in a way that lasts to future lines of your script. In this case, `somecommand` is your directory name, so you're trying to run a directory as a command, hence your error. – Charles Duffy Jan 25 '21 at 17:55
  • 1
    See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) for a general discussion of storing commands in variables. – Charles Duffy Jan 25 '21 at 17:56
  • 1
    This is an [XY Problem](https://en.wikipedia.org/wiki/XY_problem) for "How do I make my alias use the current time instead of the login time?", which is also easily fixed ([see here](https://unix.stackexchange.com/questions/199085/bashrc-lazy-substitution)) – that other guy Jan 25 '21 at 17:57
  • 1
    One of the duplicates linked has answers that involve `eval`. For the reasons given in [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048), these answers should never be used. – Charles Duffy Jan 25 '21 at 17:59
  • I'd recommend using a function instead of an alias -- much more consistent syntax, less ways to get unexpected behavior. And don't try to store the `cd` command in a variable, just execute it directly. BTW, there's also a problem if you use this between midnight and 1am, because it'll try to use the directory for 2300 hours *tonight*. Use something like `datetime=$(date -d '1 hour ago' "+%Y%m%d/%H00")` to get a consistent date and time string. – Gordon Davisson Jan 25 '21 at 18:15
  • Awesome guys, thanks for the help! – Derpy Jan 25 '21 at 23:19

0 Answers0