Home > Mobile >  Registering an alias via shell script
Registering an alias via shell script

Time:11-02

I have following shell script

#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo alias mymanager=$DIR/mymanager

The problem is, it displays command i have to copy and paste. And I cannot make it work to register alias automatically.

So Far I tried

#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
eval alias mymanager=$DIR/mymanager
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
alias mymanager=$DIR/mymanager

However, mymanager alias is not defined if I run it like this.

CodePudding user response:

An alias is only valid in the current process. When you execute your script, a new child process is started (the binary specified in the shebang line), the script executed, and the process terminated. When the process terminates, your alias disappears with it. Child processes cannot modify the parent process (they cannot change variables, they cannot introduce aliases, they cannot change their parent's working directory (cd)).

If you want to execute all lines of a script in your current shell process, use the source command (. for short). This will ignore the shebang interpreter and directly load the file.

. ./yourscript.sh # or:
source ./yourscript.sh
  • Related