How to append date and text to a file as an alias?
You can do this with a little script. One way could be:
#!/bin/bash
echo "$(date -I) : $@" >> file.txt
tail -n 1 file.txt
The $@
variable stands for anything you entered at the command line. The tail
command will echo the last line of the file to the screen.
Save this script in your ~/bin
or in your .local/bin
directory as append-to-file
. Create the directory if it does not exist. Next time you log in, either of these directories will be included in your PATH. You then can enter the command anytime. What you enter will be saved in a file file.txt
in the current working directory.
If you want something that you can pass a text message to as an argument, you should be looking at a shell function rather than an alias.
You could consider using the ts (timestamp) utility from package moreutils:
append-to-file () { printf '%s\n' "$*" | ts '%Y-%m-%d :' >> /path/to/myfile.txt ; }
If ts
is not an option, you can insert text into the format string of the date
command - but you'd need to be careful about %
characters:
append-to-file () { msg="$*"; date "+%Y-%m-%d : ${msg//%/%%}" >> /path/to/myfile.txt ; }
or (thanks to @bac0n) perhaps safer, use the bash printf
function's own time formatting capabilities - there's no need to replace %
s in this method, since the message is being passed as a string argument rather than embedded in the format string:
append-to-file () { printf '%(%Y-%m-%d)T : %s\n' -1 "$*" >> /path/to/myfile.txt ; }
If you want it echoed to the terminal as well, replace >>
with | tee -a