脚本中的全局 bash 别名

发布于 2024-09-19 17:38:37 字数 260 浏览 2 评论 0原文

我想通过脚本创建别名,并在 bash 中使用它。

即:

#!/bin/bash
alias mycmd="ls -la"

Bash:

login@host ~$: ./script
login@host ~$: mycmd
*ls output*

当然,别名应该仅适用于一个会话(而不是 .bashrc 等)。 是否可以?不幸的是我还没有找到解决方案。

I'd like to create alias by script, and use it in bash.

Namely:

#!/bin/bash
alias mycmd="ls -la"

Bash:

login@host ~$: ./script
login@host ~$: mycmd
*ls output*

Of course, alias should be available just for one session (not .bashrc etc).
Is it possible? Unfortunately I have not found a solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

兰花执着 2024-09-26 17:38:37
login@host ~$: . ./script
login@host ~$: mycmd

我相信会在你的 shell 中执行它。

login@host ~$: . ./script
login@host ~$: mycmd

Will execute it in your shell I believe.

甜妞爱困 2024-09-26 17:38:37

正确的方法是获取脚本而不是运行它。

source myscript.sh
mycmd

The proper way to do is to source the script rather than running it.

source myscript.sh
mycmd
染墨丶若流云 2024-09-26 17:38:37

创建一个脚本来完成这项工作,并将其放在 PATH 上的 bin 目录中(可能是 $HOME/bin):

$ echo "exec ls -la \"\$@\"" > $HOME/bin/mycmd
$ chmod 555 $HOME/bin/mycmd
$

如果您实际将 PATH 设置为包含 $HOME/bin,那么这是完全可靠的。

(当然,我们可以争论输入 5 个字母而不是 6 个字符的优点,但我认为这些名称是说明性的而不是真实的。)

Create a script to do the job, and put it in a bin directory on your PATH (probably $HOME/bin):

$ echo "exec ls -la \"\$@\"" > $HOME/bin/mycmd
$ chmod 555 $HOME/bin/mycmd
$

This is utterly reliable if you actually set PATH to include $HOME/bin.

(Of course, we can debate the merit of typing 5 letters instead of 6 characters, but I assume the names are illustrative rather than real.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文