0

The alias doesn't work properly until running source ~/.bashrc or source ~/.bash_aliases ONLY AFTER running the alias once first. Is there a magical way to get the $todaydir string to be replaced properly without doing that?

[myname@linux_server ~]$ cat .bash_aliases  
alias col="todaydir=$(date | awk '{print $2$3}') ; cd /home/myname/collect/$todaydir"  
[myname@linux_server ~]$ alias | grep today  
alias col='todaydir=Feb24 ; cd /home/myname/collect/'  
[myname@linux_server ~]$ source .bashrc  
[myname@linux_server ~]$ alias | grep today  
alias col='todaydir=Feb24 ; cd /home/myname/collect/'  
[myname@linux_server ~]$ col  
[myname@linux_server collect]$ alias | grep today  
alias col='todaydir=Feb24 ; cd /home/myname/collect/'  
[myname@linux_server collect]$ source ~/.bashrc  
[myname@linux_server collect]$ alias | grep today  
alias col='todaydir=Feb24 ; cd /home/myname/collect/Feb24'  
[myname@linux_server collect]$ col  
[myname@linux_server Feb24]$   
[myname@linux_server ~]$ bash --version  
bash --version  
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>  
[myname@linux_server collect]$ cat ~/.bashrc  
# .bashrc

Source global definitions

if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

User specific aliases and functions

export PATH=$PATH:~/bin
source ~/.bash_aliases

Yes, yes, bash is antique; I'm not root.

Freddy
  • 25,565

1 Answers1

1

The command substitution is evaluated when you define the alias, not when you execute the it. The same is true for the evaluation of variable $todaydir which is empty at this point. This is because you defined your alias in double quotes instead of single quotes.

This is how you meant it (I'm using a different date format):

$ alias col='todaydir=$(date | awk '\''{print $2$3}'\''); cd /home/myname/collect/$todaydir'
$ alias col
alias col='todaydir=$(date | awk '\''{print $2$3}'\''); cd /home/myname/collect/$todaydir'
$ col
-bash: cd: /home/myname/collect/25Feb: No such file or directory

But you don't need awk and the variable, use date and a format:

alias col='cd /home/myname/collect/"$(date "+%b%d")"'
Freddy
  • 25,565