Use "cd -" without any output

Try it like this:

cd - > /dev/null

You can also do:

cd - > uselessfile

This will send the output to the "uselessfile" file instead of to STDOUT.

You can also append instead of creating or overwriting the file.

cd - >> uselessfile

@erewok already answered the question, but I will take a stab at explaining what is actually happening and why you are seeing the behavior that you do.

The problem is with your redirection. You are writing:

cd - 2>&1 /dev/null

which because redirections can appear anywhere within the command line (you can confirm this yourself with something simple like echo a b 2>&1 c </etc/fstab d), after redirections are stripped actually becomes:

cd - /dev/null

See the problem? You are passing two arguments to cd, not one argument and two redirections. Since you can only ever be in one current directory at one time, cd only considers its first argument, which in this case is the -.

What you probably intended to write is a cd command with redirection of both stderr and stdout to /dev/null. There are two ways to do that.

The easiest in your case would be to simply inform the shell that you want redirection, by adding a > character. This is what @erewok is suggesting.

cd - 2>&1 >/dev/null

This first redirects stderr (file descriptor 2) into file descriptor 1 (stdout), then redirects stdout (implicit 1) into /dev/null. Note that the ordering is important; you won't get the same result if you reverse the redirections, though in some cases it may appear that you do because of how the particular program uses the respective output streams.

Alternatively, as has been suggested by @demure, you can use &> to redirect both streams at once if this syntax is supported by your shell.

cd - &>/dev/null

Do note that any of these alternatives will also silence the error when $OLDPWD no longer exists, since you are redirecting standard error output into the system black hole. If this is a concern, I would check $? afterwards; you should confirm this yourself if it is a real concern, but at least in my tests, a failed cd (whether cd $someplace or cd -) sets $? = 1 while after success $? = 0.


Maybe you can use

cd $OLDPWD

but in this case you'll need more typing :)

But you'll have an advantage: if there is any error the message will not redirect into /dev/null.

Tags:

Bash