1

I am trying to chain the commands in linux, I am using ubuntu 14.04 distribution. The aim to create a directory and go into that directory. Generally we do this

mkdir foldername
cd foldername

Perfect, when tried this

mkdir gates
cd gates 

works as expected. But things are not working as expected when using &

mkdir gates & cd gates, does not work, the error is no such file or directory. When pressed enter, it would create the directory gates in the next step. Why this is happening?. But ls & mkdir gates seems to be working fine

cuonglm
  • 153,898
gates
  • 125

1 Answers1

4

& is the shell's backgrounding operator; it places the command preceding it in the background and continues.

So

mkdir gates &
cd gates

starts mkdir gates in the background and immediately runs cd gates, which attempts to change the directory before it's created (and fails).

ls & mkdir gates

works because mkdir gates doesn't depend on anything ls does; all that happens is that ls is started in the background, outputting the directory listing, while mkdir creates the gates directory.

You're probably looking for

mkdir gates && cd gates

which will change directory only if mkdir succeeds; you may prefer

mkdir -p gates && cd gates

which won't fail if the directory already exists.

Stephen Kitt
  • 434,908