ssaquif
ssaquif

Reputation: 330

Setting an alias for a shell script, located in one of my folders

So I have this folder BashScripts that has the following directory path

/home/sadnan/BashScripts

/home/sadnan being my $HOME. This is where I intend to put my custom shell scripts. Currently there is only one named cbi.sh. The script works as expected when I run from inside the folder. Now I want to be able to run it globally. So I added the following to my .bashrc file

#For my personal Bash Scripts
if [ -d $HOME/BashScripts ]; then
 PATH="$PATH:$HOME/BashScripts"
fi

alias cbi='. ./cbi.sh'

So now when I do echo $PATH it prints out the following

/home/sadnan/.nvm/versions/node/v12.18.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/sadnan/BashScripts

So the folder seems to be added to the PATH. Which if I understand correctly should allow me to run my shell scripts globally.

And then I have also setup up an alias for the script and named it cbi

But now when I run cbi or ./cbi.sh on my terminal, this is what I get

bash: ./cbi.sh: No such file or directory

What am I doing wrong, I haven't done much shell scripting. But I thought this was the way to go.

I have also tried alias cbi=`source ./cbi.sh' and alias cbi=`sh ./cbi.sh' Neither of which worked.

Upvotes: 0

Views: 2449

Answers (2)

Nic3500
Nic3500

Reputation: 8621

./cbi.sh means "run cbi.sh from the current directory". So if you are not in /home/sadnan/BashScripts it will not work, since it cannot find cbi.sh in the current directory.

To confirm that your PATH is correctly set, execute which cbi.sh. It should return /home/sadnan/BashScripts/cbi.sh.

If you must have an alias, you could do alias cbi='/home/sadnan/BashScripts/cbi.sh'. This is the easiest way to ensure proper execution.

For all of the above to work, cbi.sh must be executable (chmod u+x cbi.sh).


If you want to source it (. cbi.sh) instead of calling it like an executable define your alias like so:

alias cbi='. /home/sadnan/BashScripts/cbi.sh'

Research the difference between executing and "sourcing" a script.



EDIT: I removed this text, following @Diego's comment.

your PATH variable will not be used at all. You should then remove the PATH addition, and

Upvotes: 1

that other guy
that other guy

Reputation: 123680

You have to run cbi.sh:

# Wrong, the file is not named 'cbi'
cbi

# Wrong, the file is not in the current directory
./cbi.sh

# Wrong, same reason as above
alias cbi='. ./cbi.sh'
cbi

# Correct, this is the name of the file:
cbi.sh

Upvotes: 2

Related Questions