Home > OS >  Running an alias in a bash script gives me `<arguments>: command not found`
Running an alias in a bash script gives me `<arguments>: command not found`

Time:02-11

I have a script with an alias _test. It works fine, but before printing the output, it does <arguments>: command not found. For example, _test -h gives line 49: -h: command not found

This is a minimal example:

alias _test='
echo Hi
'
shopt -s expand_aliases

_test -h

EDIT: For those asking about using functions, I did in fact, used to have a function instead -- but it started to cause recursion problems. I just wanted something similar to a macro -- something that acts as if the text was inserted into the script.

EDIT 2: I just realized why I kept having recursion with my function/alias. I fixed it, and I switched back to a function, but this question may help someone else.

CodePudding user response:

Remove the newlines. As written, _test -h expands to this, with a blank line above and below the echo:


echo Hi
-h

Make it a one-line alias:

alias _test='echo Hi'

In general, though, avoid aliases. They're really intended for convenience in interactive shells. In a script—or heck, even in interactive shells—it's better to use functions instead. For example:

_test() {
    echo Hi "$@"
}

For those asking about using functions, I did in fact, used to have a function instead -- but it started to cause recursion problems. I just wanted something similar to a macro -- something that acts as if the text was inserted into the script.

Were you trying to wrap an existing command, like this?

alias ls='ls --color=auto -F'

If so you can use command to prevent a function calling itself recursively. The equivalent function would be:

ls() {
    command ls --color=auto -F "$@"
}

command ls calls the ls command rather than the ls function we've just defined so we don't get stuck in an infinite recursive loop.

CodePudding user response:

Thanks to Kugelman's answer, I was able to solve it with

alias _test='
echo Hi
true'
shopt -s expand_aliases

_test -h
  • Related