别名在脚本中丢失

din*_*igo 3 macos bash shell

我想在GNU最新别名gdatedate当程序在Mac上运行

#!/bin/bash
if [[ $(uname) -eq 'Darwin' ]]; then
    alias date="gdate"
    echo 'you are on a mac!'
    type date
fi
# rest of the program
Run Code Online (Sandbox Code Playgroud)

鉴于此代码,如果我直接在终端上运行int它打印:

you are on a mac!
date is an alias for gdate
Run Code Online (Sandbox Code Playgroud)

但是,如果我像./test.sh打印一样运行脚本本身:

you are on a mac!
date is /bin/date
Run Code Online (Sandbox Code Playgroud)

为什么不从脚本中应用别名?

che*_*ner 7

默认情况下,别名不会在非交互式shell中展开.请改用功能.

if [[ $(name) -eq Darwin ]]; then
   date () { gdate "$@"; }
   echo 'you are on a mac!'
   type date
fi
Run Code Online (Sandbox Code Playgroud)