英文:
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:
我对Shell命令还很陌生,想知道是否有方法连接两个命令:
Scenario-> you check for a directory with the command ls and if it isn't there yet you connect ls with the command mkdir.
情景->你可以使用ls命令来检查目录是否存在,如果还不存在,你可以将ls与mkdir命令连接起来。
Can you connect those two? I tried ls
你能够连接这两个命令吗?我尝试过 ls
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
我试图检查我的路径中是否存在名为bar的目录,如果不存在,应该创建一个名为bar的目录。命令应该是这样的:ls bar && mkdir bar
The output of that tho is ls: bar not found . bcs obviously it wasn't created yet.
但是输出是 ls: bar not found,因为显然它尚未创建。
英文:
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 <directory> && mkdir <directory>
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.
答案1
得分: 0
&&
仅在第一个命令未成功时执行第二个命令 - 参见此问题。对于命令 ls bar && mkdir bar
,如果 bar
不存在,ls bar
将不成功,因此不会继续执行 mkdir bar
。
您可以使用 ls bar || mkdir bar
来代替 &&
,以确保第二个命令执行,即使第一个命令没有成功完成。
如果您不确定 bar
是否存在,更好的选项是 mkdir -p bar && ls bar
。mkdir -p bar
会在 bar
不存在时创建它,并且如果 bar
已经存在,不会抛出错误(在此帖子中有更好的解释)。然后,您知道在调用 ls
时该目录已存在,因此可以确保 ls
将成功完成。如果文件夹中没有内容,您就知道它是新创建的;如果有内容,您就知道它已经存在。
英文:
&&
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论