bash - 如何在 shell 脚本中创建别名?

标签 bash shell alias

<分区>

在 Linux 系统上定义别名非常简单。

从下面的示例中我们看到:I_am_only_ls_alias 别名命令为我们提供了 ls 命令的输出

 # alias I_am_only_ls_alias=ls
 # I_am_only_ls_alias

输出:

file   file1

但是当我尝试在 bash 脚本中执行相同操作时(定义别名 I_am_only_ls_alias),我得到 I_am_only_ls_alias: command not found

我的 bash 脚本示例:

alias_test.bash

#!/bin/bash

alias I_am_only_ls_alias=ls

I_am_only_ls_alias

运行 bash 脚本 - alias_test.bash

/tmp/alias_test.bash

输出:

/tmp/: line 88: I_am_only_ls_alias: command not found

所以,首先我想问:

为什么 bash 不能将命令 I_am_only_ls_alias 识别为别名?

我需要做什么才能在 bash 脚本中定义别名?可能吗?

最佳答案

来自 bash 手册页:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

所以这应该可行:

#!/bin/bash
shopt -s expand_aliases
alias I_am_only_ls_alias=ls
I_am_only_ls_alias

脚本通常使用函数,而不是别名。

关于bash - 如何在 shell 脚本中创建别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24054154/

相关文章:

bash - 子外壳中的源无法按预期工作

Git:获取 repo 中未提交行的总数

shell - 在 bourne shell 的用户定义函数中使用 getopts

php - 将不同表的不同字段存储到临时表中

bash - 如何使用 sed 从文件中获取 SOA 序列号?

json - shell 脚本解析问题 : unexpected INVALID_CHARACTER (Windows cmd shell quoting issues? )

bash - 将 stderr 和 stdout 记录到日志文件并处理 bash 脚本中的错误

shell - 如何在 Haskell 中执行一系列 shell 命令并在出现错误时中断?

ssh - SSH配置文件段落可在远程服务器上打开特定目录

postgresql - 跨模式与 typeorm 连接