linux - .sh 脚本没有正确返回变量

标签 linux bash shell echo alias

我创建了一个名为 alias.sh 的文件,我在其中放入了以下代码:

#!/bin/bash

OUTPUT="$(alias | awk -F'[ =]' '{print $2}')"
echo "${OUTPUT}"

每当我运行命令alias | awk -F'[ =]' '{print $2}' 在终端中,它以我的首选格式正确返回设置别名的列表。

但是,当我执行像 $ ./alias.sh 这样的脚本时,它只是返回一个空行。

如果我替换 别名 | 脚本就可以工作awk -F'[ =]' '{print $2}' 命令与 ls 命令。它甚至保留换行符。

谁能帮我理解为什么脚本没有返回预期的结果?

最佳答案

错误的实际原因是因为alias在shell不交互时没有扩展,

man bash 页面,

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

将下面的行添加到脚本的顶部以手动强制扩展。

shopt -s expand_aliases

然后获取脚本而不是执行

#!/bin/bash

shopt -s expand_aliases

output=$(alias | awk -F'[ =]' '{print $2}')
echo "$output"

现在将脚本作为

. ./myScript.sh

关于linux - .sh 脚本没有正确返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090797/

相关文章:

swift - NSString.appendingPathComponent(_ :) not working correctly on Linux

linux - 删除每个第 X 个文件的 Linux 脚本

bash - 将bash转换为fish函数(在fish中使用rga-fzf)

bash - 如何通过多个条件将一列拆分为另一列?

Linux:使用参数作为文件快捷方式

linux - ORA-00119 : invalid specification for system parameter LOCAL_LISTENER

linux - tomcat7 localhost :8080 is not working?时怎么办

bash - 在 Bash 中转置文件的有效方法

命令 shell 脚本中的 Linux bash -c

c++ - qt 通过 qprocess 运行 shell 命令