Home > Mobile >  Script adding alias in Linux
Script adding alias in Linux

Time:11-22

I have written this thing, but it is not working. I do not know why. The script does not create any alias. Here is my script:

#!/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

That is probably simple question, I am totally new to Linux.

CodePudding user response:

In unix derived systems, it is irregulary to have a process (child) alter the environment of the process that created it (parent). This is a sharp contrast with windows, which historically had no notion of processes. Windows, especially its command environment, owes its execution model to a 1970s system called CP/M which it was cloned from.

In windows, a batch file can alter the current shell's environment; for example, cd /temp would change the current directory of the shell. In unix derived systems this is not true. A child cannot alter the parent's environment [ of course there is an exception, below ]; so any files opened, closed, directories changed, environment variables set/reset, etc... all only affect the child.

So, while you might be able to have a script containing ``` alias bye=logout `` that alias would only exist in the script.

The exception is a concept of sourcing. A unix shell typically has a command called source (abbreviated ., as in . myscript.sh), which rather than creating a new process to run myscript.sh in, merely includes myscript.sh in the current shell.

With source, you can achieve the effect you need, after tidying up your errors mentioned in the comments. In the meantime, you should be able to source something like this ``` alias bob="I need, I need, I need"

and verify that it works.

CodePudding user response:

"==" isn't for test equal. It is a simple equal: "=" For check if it is different it is: !=

For define an alias you must use the command alias.

And you must execute the script with the command:

. ./script 

The first dot is important if not the script will be executed by a sub-shell and the alias definition will be for the sub-shell, and not the actual 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
  • Related