在 Linux 中添加别名的脚本

Script adding alias in Linux

我写了这个东西,但是没有用。我不知道为什么。该脚本不会创建任何别名。这是我的脚本:

#!/bin/bash
ans=t

while [ $ans == y ]; do
    echo "Give alias name"
    read name
    echo "Give aliast instruction"
    read instruction
    echo "alias $name='$instruction'" 
    read ans
done

这可能是个简单的问题,我是 Linux 的新手。

在 unix 派生系统中,让一个进程 (child) 改变创建它的进程 (parent) 的环境是不正常的。这与 windows 形成鲜明对比,后者在历史上没有进程的概念。 Windows,尤其是它的命令环境,其执行模型归功于一个名为 CP/M 的 1970 年代系统,它是从该系统克隆而来的。

在windows中,一个batch文件可以改变当前shell的环境;例如,cd /temp 将更改 shell 的当前目录。在 unix 派生系统中,这是不正确的。 child不能改变parent的环境[当然也有例外,见下文];所以任何文件打开、关闭、目录更改、环境变量 set/reset 等...都只会影响 child.

因此,虽然您可以拥有包含 ``` 的脚本 别名再见=注销 `` 该别名只会存在于脚本中。

例外是 采购 的概念。 unix shell 通常有一个名为 source 的命令(缩写为 .,如 . myscript.sh),而不是创建一个新进程 运行 myscript.sh中,仅包括myscript.sh在当前shell.

使用source,你可以在整理你在评论中提到的错误后达到你需要的效果。与此同时,你应该能够找到像这样的东西``` alias bob="我需要,我需要,我需要"

and verify that it works.

“==”不适用于测试相等。这是一个简单的等于:“=” 要检查它是否不同,它是:!=

要定义别名,您必须使用命令别名。

并且您必须使用以下命令执行脚本:

. ./script 

第一个点很重要,否则脚本将由 sub-shell 执行,别名定义将用于 sub-shell,而不是实际的 shell ].

#!/bin/bash
ans=t

while [ $ans != y ]; do
    echo "Give alias name"
    read name
    echo "Give aliast instruction"
    read instruction
    alias "$name=$instruction" 
    read ans
done