5

I am executing following command.

cd dirname; echo $?

This always return 0 whether of not cd is successful. This is giving me incredible headache.

How to check if cd was successful without reading its error message.

Dilawar
  • 971

4 Answers4

5

The reason may be that cd is not a shell builtin as usual but

  1. a shell function
  2. or an alias

This can be checked with type cd.

(I make the comment an answer so that the question can be "closed".)

Hauke Laging
  • 90,279
3

My stupidity!

As suggested by HaukeLaging, I did type cd. It turned out the cd was aliased to some bash function which was logging the user cd activity on the server.

I aliased cd back to cd and the script started working fine. I had the fleeting temptation to delete the question altogether first the I thought I should answer it here. I might be useful for someone else.

Dilawar
  • 971
  • 1
    I would suggest checking all aliases on your account. See for example http://unix.stackexchange.com/questions/8581/which-is-the-safest-way-to-get-root-privileges-sudo-su-or-login (there is worse) ... also whatever did it accidentally could have done it twice. – babou May 30 '13 at 07:53
  • 4
    Also think about using \cd to override the alias. – terdon May 30 '13 at 15:45
  • 3
    To remove an alias: unalias cd. To remove a function: unset -f cd. To call the builtin cd, in bash and a few other shells: builtin cd (\cd would bypass aliases but not functions). command cd would call the builtin cd in POSIX shells, but the cd command in zsh (when not in POSIX mode). – Stéphane Chazelas Sep 25 '20 at 10:01
0

The same thing happened to me. As all others mentioning, it was because my "cd" was wrapped by a function.

Anyway, this should be worked.

command cd /mnt/c/nowhere && echo y # does not console "y"
0

One solution is to prefix the call w/ the bash builtin 'command'. This will force the use of the actual binary file 'cd'

    root@ds002:~# command cd /foo
    -bash: cd: /foo: No such file or directory
    root@ds002:~# echo $?
    1