gpt4 book ai didi

Bash:bash -c 中的别名

转载 作者:行者123 更新时间:2023-12-03 08:10:08 25 4
gpt4 key购买 nike

简而言之:我怎样才能执行

bash -c "set -x; alias ll='ls -l -h'; ll"

输出为

+ alias 'll=ls -l -h'
+ ll
bash: ll: command not found

似乎 bash 会在我的“ll”之前添加一个单引号...

提前致谢!

最佳答案

有两件事阻止别名 ll 扩展:

  1. 只有在交互式 shell 中或者使用 shopt -s Expand_aliases 时,别名才会展开。

  2. 别名会在读取包含命令的行时展开(如果已展开),而不是在执行命令时展开,因此只能展开前面行中定义的别名。 (此外,bash 在执行之前会读取整个复合命令,因此您无法定义别名并在同一复合命令中使用它。这不适用于此处,但了解一下可能会很有用。)

因此,您需要将 bash 标记为交互式,并在命令行中引入换行符。例如,您可以这样做:

bash -ic "alias ll='ls -l -h'"$'\n'"ll"

但是使用函数会容易得多:

bash -c 'll() { ls -l -h "$@"; }; ll'

所有这些都记录在 Bash manual, §6.6 Aliases 中:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt

…Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

该部分最后建议使用函数:

For almost every purpose, shell functions are preferred over aliases.

关于Bash:bash -c 中的别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71075623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com