如何在 shell 中向 .bash_profile/.profile/bashrc 添加函数?

Dud*_*ude 32 shell bash profile function

我有一个将纪元时间转换为日期的函数。这是定义

date1(){
  date -d @$1
}
Run Code Online (Sandbox Code Playgroud)

我希望能够写:

$ date1 xxxyyy
Run Code Online (Sandbox Code Playgroud)

其中 xxxyyy 是我传递给函数的参数,因此我可以获得相应的日期。我明白我必须将它添加在任.bash_profile.profile.bashrc然后它来源:

$ source file
Run Code Online (Sandbox Code Playgroud)

但是,我不确定应该把它放在哪个文件中。目前,我把它放在.profile. 但是要运行它,我必须source .profile每次都这样做。

理想情况下,当计算机像环境变量一样启动时,它应该使其可用。

l0b*_*0b0 28

来自man bash

当 bash 作为交互式登录 shell 或作为具有 --login 选项的非交互式 shell 调用时,它首先从文件 /etc/profile 读取并执行命令(如果该文件存在)。读取该文件后,它会按顺序查找 ~/.bash_profile、~/.bash_login 和 ~/.profile,然后从第一个存在且可读的命令中读取和执行命令。

换句话说,你可以把它放在任何一个~/.bash_profile~/.bash_login或者~/.profile或任何文件source由这类原因ð。通常~/.profile将 source ~/.bashrc,它是“为登录 shell 执行的个人初始化文件”。

要启用它,请启动一个新的 shell,运行exec $SHELL或运行source ~/.bashrc


Dop*_*oti 18

在您的 中定义函数后.profile,添加export -f date1. 这将导出该函数以供您的登录 shell 使用。


Gil*_*il' 8

交互式 shell 的自定义进入~/.bashrc. 登录时要运行的内容进入~/.profile(或~/.bash_profile,但在以图形方式登录时通常不会加载)。

将此函数定义放在~/.bashrc.

由于 bash.bashrc在它是登录 shell 时不会加载,因此强制它这样做:编写一个~/.bash_profile包含

. ~/.profile
case $- in *i*) . ~/.bashrc;; esac
Run Code Online (Sandbox Code Playgroud)

即 load ~/.profile~/.bashrc如果 shell 是交互式的,也加载。

请参阅.bashrc 的替代方法和链接到那里的帖子。