Creating an alias for a bash script

So I have tried experimented and created an alias in .bashrc. However, when I test out the command I get:

[rkahil@netmon3 ~]$ menu
-bash: menu: command not found

Here is what I have in the .bashrc file:

# Source global definitions

if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific aliases and functions
alias menu='./menuScript.sh'
alias vi='vim'

The funny thing is when I created the alias vi, it worked. But menu does not. I have looked up previous posts on UnixStackExchange and attempted to follow other posts, but to no avail. Does anyone else have any suggestions?

Asked By: ryekayo

||

Did you remember to source your ~/.bashrc file after making the changes? Because the changes take effect in your .bashrc file after restarting your computer or simply sourcing the file.

Answered By: cbora

You should try with alias menu='bash ./menuScript.sh'. I am not currently on a Linux machine, so cannot test it myself, but it should work. When you call the alias, it doesn’t know what to do with the path, so you must include the bash at the beginning.

And resetting the terminal does help after making the change.

Answered By: Con7e

When you do

alias menu='./menuScript.sh'

you create am alias that says “that file” but doesn’t say what to actually do with it.

However, if you do

alias menu='source ./menuScript.sh'

or

alias menu='. ./menuScript.sh'

You are saying run that file.

Answered By: Michael Durrant

The reason why it worked with vim is because that is a program already callable without a direct path. You don’t have to explicitly say “I want this to be executed as a program” because vim already is one. It is hard-coded into the OS that when it receives the command vim, go and execute the file /usr/bin/vi or wherever the actual program is.

Answered By: Nathanael Morgan

There are two issues with the alias

alias menu='./menuScript.sh'
  1. It requires you to be in a particular directory when you invoke the alias. If you’re in a directory where menuScript.sh does not exist, the alias will fail to execute.

    It would be better if you specified the full absolute path to the menuScript.sh script when defining the alias, e.g.

    alias menu="$HOME/local/bin/menuScript.sh"
    

    or similar.

  2. As others have already said, another reason why the alias may fail is that the script is not executable, or that is have an invalid #!-line. Make sure that the script is executable with

    chmod +x menuScript.sh
    

    and that the first line in the script is

    #!/bin/bash
    

    or whatever the path is to bash (or whatever shell the script is written for) on your system.

Answered By: Kusalananda
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.