创建自定义 ls 但仅供手动使用
Create a custom `ls` but only for manual use
我正在考虑编写自己的 ls
命令。主要是作为一种学习经验,但我也认为我可以让它比默认设置更有用(对我来说)。
我担心如果我给 ls
添加别名,这也会干扰任何使用 ls 作为输出的 bash/sh 脚本。
有没有办法覆盖 ls
,但只有当它不在脚本(或管道)中使用时才有效?
您担心为您的 ls
版本设置别名会干扰其他进程。
让我们看看POSIX标准。
Historical versions of the KornShell have allowed aliases to be
exported to scripts that are invoked by the same shell. This is
triggered by the alias −x flag; it is allowed by this volume of
POSIX.1‐2008 only when an explicit extension such as −x is used. The
standard developers considered that aliases were of use primarily to
interactive users and that they should normally not affect shell
scripts called by those users; functions are available to such
scripts.
那么,“通常”对 bash 意味着什么?例如,哪个版本的 ls
会在 shell 脚本中使用?
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).
这意味着,您不必担心 shell 脚本 - 它们将使用 ls
.[=23= 的无别名版本]
但是管道呢?同样,我们可以将这两个手册页结合起来以获得更好的效果:
来自 bash
的手册页:
Each command in a pipeline is executed as a separate process (i.e., in
a subshell).
来自 alias
的手册页:
An alias definition shall affect the current shell execution
environment and the execution environments of the subshells of the
current shell. When used as specified by this volume of POSIX.1‐2008,
the alias definition shall not affect the parent process of the
current shell nor any utility environment invoked by the shell
也就是说,虽然您的别名不会在 shell 脚本中使用,但会在管道中使用。
我正在考虑编写自己的 ls
命令。主要是作为一种学习经验,但我也认为我可以让它比默认设置更有用(对我来说)。
我担心如果我给 ls
添加别名,这也会干扰任何使用 ls 作为输出的 bash/sh 脚本。
有没有办法覆盖 ls
,但只有当它不在脚本(或管道)中使用时才有效?
您担心为您的 ls
版本设置别名会干扰其他进程。
让我们看看POSIX标准。
Historical versions of the KornShell have allowed aliases to be exported to scripts that are invoked by the same shell. This is triggered by the alias −x flag; it is allowed by this volume of POSIX.1‐2008 only when an explicit extension such as −x is used. The standard developers considered that aliases were of use primarily to interactive users and that they should normally not affect shell scripts called by those users; functions are available to such scripts.
那么,“通常”对 bash 意味着什么?例如,哪个版本的 ls
会在 shell 脚本中使用?
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).
这意味着,您不必担心 shell 脚本 - 它们将使用 ls
.[=23= 的无别名版本]
但是管道呢?同样,我们可以将这两个手册页结合起来以获得更好的效果:
来自 bash
的手册页:
Each command in a pipeline is executed as a separate process (i.e., in a subshell).
来自 alias
的手册页:
An alias definition shall affect the current shell execution environment and the execution environments of the subshells of the current shell. When used as specified by this volume of POSIX.1‐2008, the alias definition shall not affect the parent process of the current shell nor any utility environment invoked by the shell
也就是说,虽然您的别名不会在 shell 脚本中使用,但会在管道中使用。