Bash。从两个变量定义别名

Bash. Define an alias from two vars

在问这个问题之前,我已经检查了 this, this and this 可能的相关帖子,但我无法找到解决方案。是完全不同的别名情况。我希望这不是重复的。

我有一系列可能的别名:

declare -A possible_alias_names=(
                ["command1"]="command2"
                #This is an array because there are more
                #But for the example is enough with one in the array
)

我想要的是测试command1是否存在并且可以启动。如果不可启动,则使用 possible_alias_names 创建一个别名。我的意思是,如果我们无法启动 command1,我希望能够尝试启动 command2。

我使用hash来测试系统中是否存在命令并且运行良好。我想(如果可能的话)继续使用散列。

例如,系统中不存在command1,存在command2。所以目标是检查数组中的每个键,看看是否可以启动该命令(存储在键中)。如果不存在,则创建一个别名来启动数组的相应值。

也许这样用数组更容易理解:

declare -A possible_alias_names=(
                ["thisCmdDoentExist"]="ls"
)

ls命令将存在,所以关键是能够创建一个像这样语法的别名alias thisCmdDoentExist='ls'

这是我的全部无效代码:

#!/bin/bash

declare -A possible_alias_names=(
                ["y"]="yes"
)

for item in "${!possible_alias_names[@]}"; do
    if ! hash ${item} 2> /dev/null; then
        if hash ${item} 2> /dev/null; then
            echo "always enter here because the command ${item} is not available"
        fi
        alias "${item}='${possible_alias_names[$item]}'"
        #I also tried... alias ${item}='${possible_alias_names[$item]}'
        #I also tried... alias ${item}="${possible_alias_names[$item]}"

        if hash ${item} 2> /dev/null; then
            echo "You win!! alias worked. It means ${item} is available"
        fi
    fi
done

似乎问题出在扩展上,因为在单引号之间它没有取值。我也试过 eval 失败了:

#!/bin/bash

declare -A possible_alias_names=(
                ["y"]="yes"
)

for item in "${!possible_alias_names[@]}"; do
    if ! hash ${item} 2> /dev/null; then
        if hash ${item} 2> /dev/null; then
            echo "always enter here because the command ${item} is not available"
        fi
        alias_cmd1="${item}"
        alias_cmd2="${possible_alias_names[$item]}"
        eval "alias ${alias_cmd1}='${alias_cmd2}'"
        #I also tried... eval "alias ${alias_cmd1}=\'${alias_cmd2}\'"

        if hash ${item} 2> /dev/null; then
            echo "You win!! alias worked. It means ${item} is available"
        fi
    fi
done

我从来没有得到第二个 echo 来查看 "You win!!" 消息。别名无效!我该怎么办?

这是重现问题的更简单方法:

#!/bin/bash
alias foo=echo
foo "Hello World"
hash foo

这是当你 运行 它时会发生的事情:

$ bash myscript
myscript: line 3: foo: command not found
myscript: line 4: hash: foo: not found

$ foo "Hello World"
bash: foo: command not found

这里的问题是:

  1. 脚本中默认不启用别名。
  2. hash 无法识别别名。

并且取决于您对该脚本的期望:

  1. 即使启用别名,脚本完成后它们也将不可用。

要解决这三个问题,您应该 source 来自交互式 shell 的脚本,并使用 type 而不是 hash:

$ cat myscript
alias foo=echo
foo "Hello World"
type foo

然后source它:

$ source myscript
Hello World
foo is aliased to `echo'

$ foo "Hello World"
Hello World

您设置别名的某些尝试现在可以成功运行,但最好的方法是:

key="foo"
value="echo"
alias "$key=$value"