Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias lost within script [duplicate]

Tags:

bash

shell

macos

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?

like image 255
dinigo Avatar asked Oct 25 '25 05:10

dinigo


2 Answers

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
like image 102
chepner Avatar answered Oct 27 '25 20:10

chepner


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.

like image 41
Fred Avatar answered Oct 27 '25 21:10

Fred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!