shellcommandlsmkdir

Is there a way to check for dir with ls and then create an directory with just one commmand?


I'm quite new to shell commands and wondered if there is a way to connect two commands: Scenario-> you check for a directory with the command ls and if it isn't there yet you connect ls with the command mkdir.

Can you connect those two? I tried ls && mkdir

Thanks for any tips and any Help!

I tried to check if there is the directory bar in my path, if not it should create one named bar. the commands should look something like that: ls bar && mkdir bar

The output of that tho is ls: bar not found . bcs obviously it wasn't created yet.


Solution

  • && only executes the second command if the first was not successful - see this question. For the command ls bar && mkdir bar, if bar does not exist, the ls bar will be unsuccessful and it will not continue to the mkdir bar.

    You could use ls bar || mkdir bar instead of the && to make sure the second command executes, even if the first did not successfully finish.

    A better option if you are not sure if bar exists would be mkdir -p bar && ls bar. mkdir -p bar will make bar if it does not exist, and will not throw an error if bar already exists (explained better in this post). Then, you know the directory exists by the time you call ls, and so you are confident ls will successfully complete. If there is nothing in the folder, you know it was newly created, and if there are contents, you know it already existed.