Search code examples
bashcygwin

Error when swapping an alias to a function in cygwin bash


Problem: When recreating an alias as a function in my .bashrc file an error occurs when the name of the function is the same as the previous name of the alias.

Details:

  • I have removed the prior alias altogether from my .bashrc file

  • When changing the name of the function to something that wasn't previously used it works correctly

  • The code higher up in the file seems to work without errors as well
  • [Edit] I can also run old aliases that no longer exist in my .bashrc file

Example:

When changing this:

alias npp='(/c/SolsApplications/NotePad++/notepad++.exe &> /dev/null &)'

To this:

npp()
{
    if [[ $1 != null ]]; then
        ('/c/SolsApplications/NotePad++/notepad++.exe' $1 &> /dev/null &)
    else
        ('/c/SolsApplications/NotePad++/notepad++.exe' &> /dev/null &);
    fi
}

The following error occurs when refreshing the .bashrc file:

bash: /c/Users/Owner/.bashrc: line 33: syntax error near unexpected token `('

bash: /c/Users/Owner/.bashrc: line 33: `npp()'

What I have tried:

  • Clearing my .bash_history file
  • Restarting bash
  • Searching the internet
  • Adding a space like so: "npp ()"

Solution

  • Aliases are simple prefix expansion. Thus, if you already have an alias npp provided, your function definition can be changed by it to the following:

    (/c/SolsApplications/NotePad++/notepad++.exe &> /dev/null &)() {
        if [[ $1 != null ]]; then
            ('/c/SolsApplications/NotePad++/notepad++.exe' $1 &> /dev/null &)
        else
            ('/c/SolsApplications/NotePad++/notepad++.exe' &> /dev/null &);
        fi
    }
    

    Finding the place this alias is added and removing it should suffice. If you have trouble doing so, simply unalias it immediately before defining the function:

    unalias npp
    npp() {
      ...
    }
    

    Consider also starting your interactive shell with logging, and reviewing those logs, to figure out where your alias is generated (should it be coming from a dotfile or similar):

    # This will start a new login shell, logging each command run to stderr
    # ...with source file and line number for content from scripts.
    PS4=':$BASH_SOURCE:$LINENO+' bash -x -l