I want to alias the gnu-date gdate to date when a program runs on mac
#!/bin/bash
if [[ $(uname) -eq 'Darwin' ]]; then
alias date="gdate"
echo 'you are on a mac!'
type date
fi
# rest of the program
Given this code, if i run int directly on a terminal it prints:
you are on a mac!
date is an alias for gdate
But if I run the script itself like ./test.sh in prints:
you are on a mac!
date is /bin/date
Why is the alias not being applied from the script?
By default, aliases are not expanded in a non-interactive shell. Use a function instead.
if [[ $(name) -eq Darwin ]]; then
date () { gdate "$@"; }
echo 'you are on a mac!'
type date
fi
Using a function will in many cases be the right solution. Anytime you have a function-based solution, do that.
However, there are things you cannot do with a function, most notably anything having to do with modifying the positional parameters of the calling context, and you can force alias expansion in a shell script by enabling the corresponding option :
shopt -s expand_aliases
You have to be aware of and control what aliases exist in your script to avoid unexpected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With