How to mkdir only if a dir does not already exist?

2019-01-05 06:48发布

I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that mkdir throws when it tries to create an existing directory.

Any thoughts on how best to do this?

13条回答
Animai°情兽
2楼-- · 2019-01-05 07:26

You can either use if loop to check if directory exists or not, if it does not exits than create the directory.

1) dir=/home/dir_name

if [ ! -d $dir ]
then
     mkdir $dir
else
     echo "Directory exists"  
fi

2) You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

mkdir -p $dir

mkdir -p also allows to create the tree structure of the directory. If you want to create the parent and child directories using same command, can opt mkdir -p

mkdir -p /home/parent_dir /home/parent_dir/child1 /home/parent_dir/child2
查看更多
登录 后发表回答