Skip to content
Advertisement

Command works in terminal but not as alias in profile.d

I have a problem regarding an alias file in /etc/profile.d/. This isn’t anything important. I’m just interested why it isn’t working as expected.

So basically I have the file 00-alias.sh at the path mentioned above and I wanted to make a shortcut which reads a specific line of a file. So this is my code:

alias lnn='sed -n "${1}p" < "${2}"'

With that code I should be able to perform a command like

$ lnn 4 test.txt

However, this doesn’t work. I simply get the error

-bash: : No such file or directory


Now I thought, ok, maybe relative paths aren’t working because the file is located at the path /etc/profile.d/00-alias.sh

So I went ahead and made a new alias like

alias pwd2='echo $(pwd)'

Then updated the profile.d with

source /etc/profile.d/00-alias.sh

And just tried pwd2 but that echoed the path I was currently in. So in theory the file can be found with the command I wrote. I still tried to pass the file to my alias with absolute path like

$ lnn 4 /var/test.txt

Still same error as above.


But, if I enter the command of the alias in the terminal like

sed -n "4p" < test.txt

It works perfectly fine. No matter if I put quotes around test.txt


And here is another weird thing: If I write

alias lnn='sed -n "${1}p" < ${2}'

without the quotes around ${2} I get the error

-bash: ${2}: ambiguous redirect

In the terminal it works just fine…

So, what am I doing wrong? Does anyone have an idea on this? I’d love to know my mistake. But as I said, this isn’t a real problem as I’m just curious why bash behaves like that.

Advertisement

Answer

Aliases in bash do not take parameters of any form. Save the pain and use a function instead.

function lnn() {
    sed -n "${1}p" < "${2}"
}

Add the function to the file 00-alias.sh and source it once before calling the function from command-line.

source /etc/profile.d/00-alias.sh
lnn 4 test.txt

See more information at BashFAQ/80: How can I make an alias that takes an argument?

You can’t. Aliases in bash are extremely rudimentary, and not really suitable to any serious purpose. The bash man page even says so explicitly:

An excerpt from the GNU bash man page, about aliases

.. There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used.


On a side note the problem has nothing to do with relative paths (or) so, just remember aliases are not allowed in scripts. They’re only allowed in interactive shells. If you’re writing a script, always use a function instead.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement