1

I am trying to create an alias in .bashrc to time-stamp a directory. Obviously, it's not working out too well for me. For example:

under .bashrc

alias testit="export testor=$(date +%d);mkdir ~/Desktop/$testor"

result:

~> testit
mkdir: cannot create directory ‘/home/SJL/Desktop/’: File exists

now if I run in command instead

~> export testor=$(date +%d)
~> mkdir ~/Desktop/$testor

directory created, no problem.

Now if I run instead:

~> export testor=$(date +%d);mkdir ~/Desktop/$testor

again, no problem.

going back to using the alias stated in .bashrc it does not work.

It's really curious because I've done similar things many many many times, but it seems that there's something going on/wrong with the date formatting.

I would really appreciate your input.

Kusalananda
  • 333,661

1 Answers1

1

When you create the alias, $testor has no value, and so the alias will be

export testor=13;mkdir ~/Desktop/

You can see what an alias expands to with alias aliasname.

To fix this, use single quotes instead of double quotes. This defers the expansion of variables and command substitutions until you actually invoke the alias.

If you don't need $testor for anything else, just use

alias tester='mkdir "$HOME/Desktop/$(date '+%d')"'

Reading your comments, this would also work:

alias makedir='mkdir "$HOME/Desktop/$(date '+%d')"'
alias copyfile='cp somefile "$HOME/Desktop/$(date '+%d')"

Or, alternatively, a more elaborate shell function that allows for copying any file to the folder (which you would never be able to do with an alias).

copyfile () {
    destfolder="$HOME/Desktop/$(date '+%d')"
    if [ -d "$destfolder" ]; then
        mkdir "$destfolder"
    fi
    cp "$1" "$destfolder"
}

This defines a function called copyfile that will use cp to copy the file given on the command line to a date-stamped folder. If the folder does not exist, it is created.

Kusalananda
  • 333,661