I'd like ls to display current date and time as a side effect every time I use
ls. How do I go about changing what a command does?
One option would be to create an alias which calls
alias ls='date;ls'. Here is an example:
$ touch a b c $ ls a b c $ alias ls='date;ls' $ ls Mon Oct 14 10:37:29 BST 2013 a b c
Define PS1 variable for your shell, this is the place where you should see whatever you want in your shell.
export PS1="\t [\u@\h \W]\$ " 12:01:58 [user@host ~]$ ls /etc/fstab /etc/fstab 12:02:00 [user@host ~]$ ls /etc/motd /etc/motd
I don't understand why you would like to do this. Maybe you could share what you are really trying to achieve and we could help you find a better solution.
What I personally do is edit my PS1 line. My PS1 line displays a lot of information in the prompt, something like this:
As you can see, it displays a wealth of information apart from the Date and Time. In order to show the date and time in your PS1, add
\@ for displaying the time and
\d for displaying the date.
Answering your question explicitly, you could create an alias in your
.bashrc. To do this, add the following line to your
alias ls='date && ls'
You stated that you don't want to change how a command works. While here it may seem like the opposite, but you must understand how aliases work in order to appreciate the fact that this does not really change the
ls command. If you do execute ls from within a script, the command is invoked in a subshell which will prevent the parent shell from enforcing your alias rules on it. Hence, no scripts calling
ls will break because the output format changed.
EDIT: Since some others may be interested in the PS1 line itself, you can find the relevant details here. Beware, it is quite large and if you have directories that have thousands of files, there will be a noticeable lag in the performance of the shell.