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?

  • 1
    Why are you using $@ at all? – Wildcard Aug 15 '19 at 18:57
  • @Wildcard Because I had copy/pasted that line from someone else who was apparently also a beginner like me. :S – Théophile Aug 16 '19 at 15:00
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
|improve this answer|||||
  • Amazing! Thank you. – Théophile Aug 15 '19 at 19:01
  • 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. – Théophile Aug 15 '19 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.