Issue
Hi there trying to add an argument to an alias in bash. I'm using a Mac. I've searched a number of related questions: Alias in Bash, Alias in Bash with autocomplete, and a few others yet still can't sort this out. I know I need to use a function to create an alias that takes an input but it's unclear if its meant to look like any of the below options. All inputs in .bash_profile.
function mins_ago () { `expr $(date +%s) - 60 \* "$1"`; }
alias mins_ago = function mins_ago () { `expr $(date +%s) - 60 \* "$1"`; }
alias mins_ago = "function mins_ago () { `expr $(date +%s) - 60 \* "$1"`; }"
alias mins_ago = function mins_ago () { `expr $(date +%s) - 60 \* $1`; }
None of these seem to work. I either get a syntax error or it doesn't recognize the argument.
What is the actual line you'd put in .bash_profile
to sort this properly? Thank you in advance. Is the alias
bit included or do I just proceed to the function definition?
Solution
Bash aliases don't support arguments, so you need to use a bash function, and use the bash
arithmetic operator $(())
function mins_ago() {
printf "%s" "$(( $(date +%s) - (60 * $1) ))"
}
Add the above function in .bash_profile
, and now testing it in the command-line,
date +%s
1485414114
value="$(mins_ago 3)"
printf "%s\n" "$value"
1485413834
(or) without a temporary variable to convert to readable format in GNU date
, do
printf "%s\n" "$(date -d@$(mins_ago 3))"
Answered By - Inian