相关疑难解决方法(0)

即使使用 shopt expand_aliases,bash 别名也不会扩展

我想在bash -c构造中运行别名。

bash手册说:

当 shell 不是交互式时,别名不会被扩展,除非expand_aliasesshell 选项是使用设置的shopt

在这个例子中,为什么显式hi设置时找不到别名expand_aliases

% bash -O expand_aliases -c "alias hi='echo hello'; alias; shopt expand_aliases; hi"
alias hi='echo hello'
expand_aliases  on
bash: hi: command not found
Run Code Online (Sandbox Code Playgroud)

我在跑GNU bash, version 5.0.0(1)-release (x86_64-pc-linux-gnu)

上下文:我希望能够以空闲优先级运行别名,例如包含以下内容的脚本:

#!/bin/bash
exec chrt -i 0 nice -n 19 ionice -c 3 bash -c ". ~/.config/bash/aliases; shopt -s expand_aliases; $(shell-quote "$@")"
Run Code Online (Sandbox Code Playgroud)

我想避免使用,bash -i因为我不想.bashrc被阅读。

bash alias

9
推荐指数
2
解决办法
3190
查看次数

为什么别名在里面不起作用?

.bashrc设置了一堆别名供我根据需要使用,然后自动运行其中一个。

事实证明,与使用交互式 shell 相比,这会导致自动脚本 ssh 进入我的机器时出现一些问题。所以,为了解决这个问题,我把它们放在一个 if 块中,这样它们就不会被定义或运行那些自动化脚本......

if [ -n "$TERM" ] && [ "$TERM" != "dumb" ] ; then
    alias short='long command here'
    alias another='very long command here'
    # ...

    short
fi
Run Code Online (Sandbox Code Playgroud)

只为看short: command not found

让我们将其减少到最低限度......

$ cat alias.sh
alias foo='echo hi'
foo
Run Code Online (Sandbox Code Playgroud)
$ sh alias.sh
hi
Run Code Online (Sandbox Code Playgroud)
cat alias-in-if.sh
if true ; then
        alias foo='echo hi'
        foo
fi
Run Code Online (Sandbox Code Playgroud)
sh alias-in-if.sh
alias-in-if.sh: line 3: foo: command not found
Run Code Online (Sandbox Code Playgroud)

为什么第一个脚本有效,而不是第二个?

(我已经回答了我自己的问题。)

bash alias

6
推荐指数
1
解决办法
299
查看次数

标签 统计

alias ×2

bash ×2