0

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.

user16217248
  • 3,119
  • 19
  • 19
  • 37
Sveppg
  • 3
  • 1
  • 1
    You can try `mkdir -p bar` – Fravadona May 24 '23 at 14:11
  • thanks a lot, i figured a pipe would do the job so ls bar | mkdir bar is it – Sveppg May 24 '23 at 14:12
  • `ls` is the wrong tool to test if a directory exists. If you want to test that the directory `foo` exists, use `test -d foo`. But in this case, you don't really want to bother checking if the directory exists; just attempt to create it with `mkdir -p foo`. Even if you do test and write `test -d foo || mkdir foo`, you have introduced a classic race condition; the test determines that `foo` does not exist, but some other process creates it before the `mkdir` is executed. – William Pursell May 31 '23 at 03:09
  • Shell command questions belong on [unix.se] or [ubuntu.se]., This site is for programming-related questions only. You can find more information in the [help]. – Ken White May 31 '23 at 03:21

1 Answers1

0

&& 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.

mickey
  • 476
  • 5
  • 18