Search code examples
linuxgoaliassubshell

How to list all the linux aliases


I am aware that in Linux I can use the alias command to get a list of defined aliases. I am now trying to do the same through Go code with:

func ListAlias() error {
    out, err := exec.Command("alias").Output()
    if err != nil {
        fmt.Println(err)
        return err
    }
    fmt.Println(out)
    return nil
}

but all that were returned were:

exec: "alias": executable file not found in $PATH

I tried looking for where the actual binary of alias is but that leads nowhere either:

$whereis alias
alias:

The alternative I've considered is to parse the ~/.bashrc file for the list of aliases defined but I have encountered this scenario where the bashrc lists another custom_aliases.sh file and all the aliases are listed there. That's why I am trying to use the alias command to list all the aliases.


Solution

  • alias isn't an executable but a shell builtin. You can easily see that by running

    $ type alias
    alias is a shell builtin
    

    Therefore you need to call the shell's alias command depending on which shell you're using. For example with bash you'll need to use

    out, err := exec.Command("/bin/bash", "-c", "alias").Output()
    

    But that still won't give you the answer because bash doesn't source the .bashrc file in that case so aliases won't be available in the subshell. You'll need the --rcfile or --login/-l option and also need to specify the shell as interactive with -i

    out, err := exec.Command("/bin/bash", "-lic", "alias").Output()
    // or
    out, err := exec.Command("/bin/bash", "--rcfile", "~/.bashrc", "-ic", "alias").Output()
    

    exec.Command("/bin/bash", "-ic", "alias") would also possibly work depending on where your aliases are sourced. Other shells like zsh, sh, dash... may source different files with different options, so check your shell's documentation if -ic or -lic doesn't work