6

If I enter

cd - 

in the command line, I go to previous location I was at. I want to do something like (obviously the below line doesn't actually work):

mv -/* .

To copy everything from the previous directory to where I currently am, without having to explicitly type out the entire previous directory. Is this possible? (On Ubuntu 16.04?, using bash)

  • "pwd" means password and does not make sense in the rest of the context of your question. – music2myear Jan 19 at 4:41
11

How do I refer to the previous directory I was in on the command line of in a script?

A couple of different ways:

  • Use the $OLDPWD variable

    Source: Bash - $OLDPWD | bash Tutorial

  • To use the - shortcut prefix it with a ~

    ~-

    Tilde Expansion

    If a word begins with an unquoted tilde character ('~'), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the HOME shell variable. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.

    If the tilde-prefix is '~+', the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is '~-', the value of the shell variable OLDPWD, if it is set, is substituted.

    Source: How-To: shell expansion - Linux - SS64.com

Examples:

$ ls
bin  sh.exe.stackdump  test  test.txt
$ cd test
$ ls
test.sh
$ ls $OLDPWD
bin  sh.exe.stackdump  test  test.txt
$ ls ~-
bin  sh.exe.stackdump  test  test.txt
$
| improve this answer | |

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.