I am writing a program in Go that sends some commands. I can run any command that is in the $PATH. I check that the command is runnable with the LookPath function.
path, err := exec.LookPath("pwd")
and then run it with the following command:
func Run(command string, args []string) string {
cmd := exec.Command(command, args...)
output, err := cmd.CombinedOutput()
if err != nil {
logging.PrintlnError(fmt.Sprint(err) + ": " + string(output))
return ""
}
return string(output)
}
The Run("pwd", "")
is working But if I am using an alias, it doesnt' work.
For instance, I have alias l='ls -lah'
in my ~/.bash_aliases
file, but when I want to run that command in Go, it doesn't work.
Run("l")
is not working.
I have the following error message :
exec: "l": executable file not found in $PATH:
I tried as well to use another method to run some alias' command.
func RunCmd(cmd string) string {
out, err := exec.Command(cmd).Output()
if err != nil {
logging.PrintlnError("error occured")
logging.PrintlnError(fmt.Sprint(err))
}
fmt.Printf("%s", out)
return string(out)
}
But it is not working as well.
Do you know what function I can use to launch a command that is defined as an alias in my shell? I tried to launch bash -c cmd
but unfortunately as well.
Thanks
If you want to launch a command that is defined as an alias in your ~/.bashrc
or~/.bash_aliases
files, you can use the bash -c cmd
command described in the other comments. Nevertheless, you must implement it in a proper way in Go. Here is the command:
exec.Command("/bin/bash", "-c", "aliasCmd "+ _alias_arguments)
However, you should not have your program to rely on a user defined alias. ;-)