I am having trouble using the date function along with the vim command in bash

46 Views Asked by At

I have recently started journaling and I wanted to create a program to make the process a little easier. The program uses bash to mount an external hard drive (with a known name) and open the journal folder on that drive, then open vim in that folder while naming the file with the current date.

Here is the program (put in ~/.bin and named journal):

#!/bin/bash

CURRENTDATE=$'date +"%m-%d-%y"'
udisksctl mount -b /dev/sda2
cd /run/media/harrison/Backup\ Disk/journal
vim ${CURRENTDATE}.txt

So far it does mostly what I want. It mounts the disk successfully and opens vim. When I type something unique and close vim with :wq, and change directory to where the new file should be, there is a new file named "date" containing the text I wrote. The only problem is that the name is wrong. The new file should be named something like "03-27-24.txt", instead of "date". How do I get the program to name the file the current date? In case it matters, I am using Arch Linux.

1

There are 1 best solutions below

1
Mark Reed On

$'...' is just a literal string (specifically an ANSI string, that follows the string literal conventions of ANSI C); it doesn't run that string as a command. For that, you want $(...).

CURRENTDATE=$(date +"%m-%d-%y")

Except there's no reason to name a variable in all-caps except to mark it as special (either to the shell, or because you're exporting it into the environment for use by some other program, or whatever). Better to use lowercase:

current_date=$(date +%m-%d-%y)

You also don't need the curly braces when you reference it to get its value, though they don't hurt. But you should put quotation marks around the expansion – all expansions, in fact. They aren't strictly needed here, just because you picked a date format that doesn't have any spaces or special characters in it, but if you were to leave the quotes off and that changed in the future your script would break. So it's just a good habit to get into:

vim "$current_date.txt"