Search code examples
bashterminalhistoryrm

Remove last visited directory in terminal


The - command returns the last visited directory in the terminal. If I try to delete the last directory like that rm -rf `-` nothing happens. That means the last visited folder still exists.


Solution

  • Beware that - is not a command, it has the meaning you describe only when used as an argument to the cd command (see the OPERANDS section of the POSIX man page for cd). If you try to execute it you should get

    $ `-`
    -bash: -: command not found.
    

    Note that you do not see the error message because of the -f parameter. Remove it and you will get

    $ rm -r `-`
    -bash: -: command not found
    usage: rm [-f | -i] [-dPRrvW] file ...
           unlink file
    

    The previous directory is available in the $OLDPWD env variable. So your command should be

    rm -rf "${OLDPWD}"
    

    As a side note - also has the special meaning of stdin when used as a file name, for many GNU command. And also note that the backtick construct is deprecated in favour of the $() construct.