I am trying to add an alias to my .bashrc so that running the following command > push 123 will add the line 2017-08-29/push/123 (with current date) to the end of a file.

adding the alias: alias push='date +%F/push/ >> log.txt ; echo $1 >> log.txt' almos does the trick, this adds two rows as follows


Please help me make it a single row.

1 Answer 1

push () { date "+%F/push/$1" >> /tmp/pushlog.txt; }

This defines a shell function that appends the string to the /tmp/pushlog.txt file.

The format string used with date incorporates the first command line argument of the shell function.

bash-4.4$ push 123
bash-4.4$ push "hello world"
bash-4.4$ push "%s"
bash-4.4$ cat /tmp/pushlog.txt
2017-08-29/push/hello world

If you're planning to use push to push strings that may be interpreted by date (like the last example), and if that's not what you want, then use this instead:

push () { printf '%s/push/%s\n' "$(date '+%F')" "$1" >> /tmp/pushlog.txt; }

The reason you get an unwanted newline in your file is that date outputs a newline at the end of its output. This newline is removed when using date in $(...) as I did in the second implementation of my shell function above.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.