0

I have aliased pushd in my bash shell as follows so that it suppresses output:

alias pushd='pushd "$@" > /dev/null' 

This works fine most of the time, but I'm running into trouble now using it inside functions that take arguments. For example,

test() { pushd . ... } 

Running test without arguments is fine. But with arguments:

> test x y z bash: pushd: too many arguments 

I take it that pushd is trying to take . x y z as arguments instead of just .. How can I prevent this? Is there a "local" equivalent of $@ that would only see . and not x y z?

2
  • 1
    Why are you using $@ at all? Commented Aug 15, 2019 at 18:57
  • @Wildcard Because I had copy/pasted that line from someone else who was apparently also a beginner like me. :S Commented Aug 16, 2019 at 15:00

1 Answer 1

5

Aliases define a way to replace a shell token with some string before the shell event tries to parse code. It's not a programming structure like a function.

In

alias pushd='pushd "$@" > /dev/null' 

and then:

pushd . 

What's going on is that the pushd is replaced with pushd "$@" > /dev/null and then the result parsed. So the shell ends up parsing:

pushd "$@" > /dev/null . 

Redirections can appear anywhere on the command line, so it's exactly the same as:

pushd "$@" . > /dev/null 

or

> /dev/null pushd "$@" . 

When you're running that from the prompt, "$@" is the list of arguments your shell received so unless you ran set arg1 arg2, that will likely be empty, so it will be the same as

pushd . > /dev/null 

But within a function, that "$@" will be the arguments of the function.

Here, you either want to define pushd as a function like:

pushd() { command pushd "$@" > /dev/null; } 

Or an alias like:

alias pushd='> /dev/null pushd' 

or

alias pushd='pushd > /dev/null 
1
  • I had actually thought of writing it as a function, but I didn't know about command yet, so of course it created an infinite loop. Commented Aug 15, 2019 at 21:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.