John Hoffman
John Hoffman

Reputation: 18667

How do I set an alias from a shell script?

I'm trying to set an alias that applies to the current shell (the shell I'm running the script from) from a shell script. The alias is for cd-ing into the folder of the script. Here's the (not working) script:

#!/bin/bash
shopt -s expand_aliases

DIR=$(cd $(dirname "$0"); pwd) # Detect the folder of the script.
alias cdr="cd $DIR" # cd into the folder.

I quickly realized that this didn't work because the alias it made was pertinent to the script's subshell.

Then, I tried to source the file (as in . makeAlias.sh). However, this produced an error: dirname: illegal option -- b.

How do I write a bash script that makes an alias relevant to the outer shell (the shell running the script)?

Upvotes: 0

Views: 392

Answers (2)

tripleee
tripleee

Reputation: 189908

The immediate problem is that the value of $0 is now -bash. You might want to refactor your code to use a different reference point, or simply hard-code the path.

To answer the "how do I ...?" you aren't doing anything wrong, it's just that the logic has to be adapted to a different environment -- specifically, when you source a script, $0 is that of the parent process, not the name of the script you are sourcing.

Depending on what you are trying to accomplish, maybe this alternative design could work?

newr () { r=$(pwd); }
cdr () { cd "$r"; }
newr

That is, cdr simply changes directory to whatever the variable r contains. The function newr can be used to conveniently set r to your current working directory. You'd define these in your .bashrc or similar, and use them interactively

Upvotes: 1

./makeAlias.sh will be executed in a sub-shell and the changes made apply only the to sub-shell. Once the command terminates, the sub-shell goes and so do the changes.

Sourcing the file using . ./makeAlias.sh or source ./makeAlias.sh will read and execute commands from the file-name argument in the current shell context, that is when a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes.

Upvotes: 1

Related Questions