.sh 脚本没有 return 变量正确

.sh script doesn't return variable correctly

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

#!/bin/bash

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

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

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

如果我将 alias | awk -F'[ =]' '{print }' 命令替换为 ls 命令,该脚本将起作用。它甚至保留换行符。

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

您在 AWK 脚本中使用 </code>。但是,它被 shell 替换为 <em>shell</em> 脚本的第二个参数,这没什么。您需要转义美元符号,如 <code>$2。或者不在子 shell.

周围使用双引号 "

actual错误的原因是因为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 }')
echo "$output"

现在将脚本来源为

. ./myScript.sh