What command can be used to check if a directory exists or not, within a shell script?
相关问题
- How to get the return code of a shell script in lu
- Is shmid returned by shmget() unique across proces
- Invoking Mirth Connect CLI with Powershell script
- Why should we check WIFEXITED after wait in order
- Emacs shell: save commit message
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- Making new files automatically executable?
- Reverse four length of letters with sed in unix
- Launch interactive SSH bash session from PHP
- What does it take to be durable on Linux?
As per Jonathan comment:
If you want to create the directory and it does not exist yet, then the simplest technique is to use
mkdir -p
which creates the directory — and any missing directories up the path — and does not fail if the directory already exists, so you can do it all at once with:To check if a directory exists you can use simple if structure like this:
You can do it also in negative
Note: Be careful, leave empty spaces on either side of both opening and closing braces.
With the same syntax you can use:
Great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:
will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.
I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:
This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to stdout (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.
Shorter form:
A simple script to test if dir or file is present or not:
A simple script to check whether the directory is present or not:
The above scripts will check the dir is present or not
$?
if the last command sucess it returns "0" else non zero value. supposetempdir
is already present thenmkdir tempdir
will give error like below: