I use this shell pipeline to get a SQL dump using the terminal:

$ cd var/lib/mysql && mysqldump -uroot -p"craft" --add-drop-table craft > ~/../docker-entrypoint-initdb.d/base.sql && cd ~/..

As can be seen, I entered the var/lib/mysql directory and create the dump to a file and come back from where I was initially.

The command is correct, but, I guess it can be written concisely like without entering directly the var/lib/mysql directory.

Can anyone suggest that?

  • More generally ( cd some_place && do_stuff ) Note the parenthesis. Mar 19 '19 at 11:27

To be honest, I don't see a reason for the two calls to cd at all.

You don't seem to use the directory that you cd into for anything. You give an absolute path for the location of the database dump. If any custom MySQL configuration file is needed, that would be picked up from the user's home directory in any case.

You could therefore, quite likely, just use

mysqldump -uroot -p"craft" --add-drop-table craft \
    > ~/../docker-entrypoint-initdb.d/base.sql

regardless of what directory you run that from.

  • Yes, my understanding is not correct that I need to enter the var/lib/mysql to run the command for the dump.
    – Arefe
    Mar 19 '19 at 10:32

In this case, you don't need to change working directory at all (as answered by Kusalananda). However, if you're dealing with commands that do need a particular working directory, then there are a couple of things to know that will make it easier for you.

Firstly, since cd sets the OLDPWD variable, we can use that to return to the original directory, without having to know its name. Secondly, we probably want to return whether or not the command succeeded, so use ; rather than && there:

cd "$workdir" && somecommand ; cd "$OLDPWD"

That's still unreliable if the first cd fails; to be more robust, we really need

if cd "$workdir" ; then somecommand ; cd "$OLDPWD" ; fi

Even at this point, we're struggling if we need the exit status of somecommand after this.

It's usually best to run the command in a subshell, and change only the subshell's working directory:

( cd "$workdir" && somecommand )

This last approach is what I normally use and recommend, unless you're doing something which isn't possible from a subshell, such as setting variables for subsequent commands.

  • 1
    cd - is even more portable than cd "$OLDPWD" Mar 19 '19 at 12:05
  • The last approach is also what I normally use. Mar 19 '19 at 12:38
  • @Stéphane, with the caveat that it also (in POSIX, at least) also prints the new working directory, so consider sending its output to /dev/null. Mar 19 '19 at 13:14

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.