Only mkdir if it does not exist [duplicate] - bash

This question already has answers here:
How to mkdir only if a directory does not already exist?
(17 answers)
Closed 8 years ago.
In my bash script I do:
mkdir product;
When I run the script more than once I get:
mkdir: product: File exists
In the console.
So I am looking to only run mkdir if the dir doesn't exist. Is this possible?

Do a test
[[ -d dir ]] || mkdir dir
Or use -p option:
mkdir -p dir

if [ ! -d directory ]; then
mkdir directory
fi
or
mkdir -p directory
-p ensures creation if directory does not exist

Use mkdir's -p option, but note that it has another effect as well.
-p Create intermediate directories as required. If this option is not specified, the full path prefix of each oper-
and must already exist. On the other hand, with this option specified, no error will be reported if a directory
given as an operand already exists. Intermediate directories are created with permission bits of rwxrwxrwx
(0777) as modified by the current umask, plus write and search permission for the owner.

mkdir -p
-p, --parents
no error if existing, make parent directories as needed

Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi

Related

Unix Bash Script Create Directory parent and child method

I'm trying to create directory using if condition statement, while running script i am not able to find any expected result from the script, but when i am running manually only mkdir command alone its creating as we expected; here the sample code.
#!/bin/bash
dir_path=/tmp/opt/app/software/{A,B,C,D}
if [[ -d $dir_path ]]; then
mkdir -p /tmp/opt/app/software/{A,B,C,D}
fi
can you please advise, how we can create this..
dir_path is a "list" of directory paths due to the {} parameter expansion. If you write this out:
dir_path=/tmp/opt/app/software/A /tmp/opt/app/software/B /tmp/opt/app/software/C /tmp/opt/app/software/D
This is what's being used in the test of the if statement.
Either you want to iterate over the list of sub directories, or just pass them to mkdir. mkdir simply won't create the directory if it already exists.
Your mkdir command actually expands out to:
mkdir -p /tmp/opt/app/software/A /tmp/opt/app/software/B /tmp/opt/app/software/C /tmp/opt/app/software/D
If you want to itterate and still do a check (which while needless in this example can still be useful other times.)
# Declare the variable `dirs` to be an array and use
# parameter expansion to populate it
declare -a dirs=(/tmp/opt/app/software/{A,B,C,D});
# Iterate over the array of directory names
for dir in ${dirs[#]}; do
if [ ! -d "$dir" ]; then
# The directory does not exsist
mkdir -p "$dir"; # Make the directory
fi
done

trying to create a script with timestamp [duplicate]

This question already has answers here:
Why can't I change directories using "cd" in a script?
(33 answers)
Closed 3 years ago.
I'm fairly new to bash scripting.
I'm trying to create a directory with a timestamp and then cd into the directory.
I'm able to create a directory and can cd into it the directory with one command.
mkdir "build" && cd "build"
I can create the directory with data then cd into it.
mkdir date '+%m%d%y' && cd date '+%m%d%y' I am able to create this dir and cd into it with one command.
Here is my bash script:
#!/bin/bash
# mkdir $(date +%F) && cd $(date +%F)
mkdir build_`date '+%m%d%y'` && cd build_`date '+%m%d%y'`
I need to create the directory with build_date '+%m%d%y' in the title then cd into that folder.
I've looked online but am unable to come up with a solution.
Thank you.
Try this:
#!/bin/bash
build_dir="build_$(date '+%m%d%y')"
mkdir $build_dir && cd $build_dir
Best is to name your Folders YYYY.MM.DD like build_2019.11.21
#!/bin/bash
DIRECTORY="build_$(date '+%Y.%m.%d')"
if [ ! -d "$DIRECTORY" ]; then
# checking if $DIRECTORY doesn't exist.
mkdir $DIRECTORY
fi
cd $DIRECTORY
touch testfile
Here's a script that uses /usr/bin/env bash and the builtin command printf instead of /bin/date.
#!/usr/bin/env bash
date="$(printf '%(%m%d%y)T' -1)"
[[ -d build_"${date}" ]] || mkdir build_"${date}"
cd build_"${date}"
# do something useful here
# ...
However, changing directory in a script (subshell) is not much use on its own, as your current working directory ($PWD) will be the same after the script exits.
If you want to have the current shell session change into the new directory, use a shell function.
mkbuild() {
date="$(printf '%(%m%d%y)T' -1)"
[[ -d build_"${date}" ]] || mkdir build_"${date}"
cd build_"${date}"
}
Then run it:
$ echo $PWD
/tmp
$ mkbuild
$ echo $PWD
/tmp/build_112119

How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')"

mkdir $(date '+%d-%b-%Y')
then cd to the dynamically created directory
How to "cd" to a directory which is created using "mkdir $(date '+%d-%b-%Y')" and do the operations by moving into the created directory in bash script
Simple way would be, you store the directory name in a variable
dirname=$(date '+%d-%b-%Y')
if [ -n "$dirname" ]; then
mkdir "$dirname"
if [ -d "$dirname" ]; then
cd "$dirname"
fi
fi
Added some error handling and also if your file is written in Windows and being run in an unix environment or vice-versa, I would recommend using dos2unix which will handle the new line character conversions (this is for the ? characters OP is seeing in ls).
Can you show me your case?
In most cases, you should not cd in to the directory. Use absolute path instead:
Good practice:
mkdir /tmp/mydir/
cp -R /usr/local/example/ /tmp/mydir/
sed 's/foo/bar/g' /tmp/mydir/afile
Bad practice:
mkdir /tmp/mydir/
cd /tmp/mydir/
cp -R /usr/local/example/ .
sed 's/foor/bar/g' afile
P.S.
Subj:
$ mkdir $(date '+%d-%b-%Y')
$ cd $(date '+%d-%b-%Y')
$ pwd
/Users/user/18-Feb-2019
In Bash, $_ expands to the last argument to the previous command. So you could do:
mkdir $(date '+%d-%b-%Y')
cd $_
In a real Bash program you would want to quote the expansions (use Shellcheck on your code to check for missing quotes), and check for errors on both mkdir and cd.

BASH redirect create folder

How can I have the following command
echo "something" > "$f"
where $f will be something like folder/file.txt create the folder folder if does not exist?
If I can't do that, how can I have a script duplicate all folders (without contents) in directory 'a' to directory 'b'?
e.g if I have
a/f1/
a/f2/
a/f3/
I want to have
b/f1/
b/f2/
b/f3/
The other answers here are using the external command dirname. This can be done without calling an external utility.
mkdir -p "${f%/*}"
You can also check if the directory already exists, but this not really required with mkdir -p:
mydir="${f%/*}"
[[ -d $mydir ]] || mkdir -p "$mydir"
echo "something" | install -D /dev/stdin $f
try
mkdir -p `dirname $f` && echo "something" > $f
You can use mkdir -p to create the folder before writing to the file:
mkdir -p "$(dirname $f)"

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

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.
How can I best do this?
Try mkdir -p:
mkdir -p foo
Note that this will also create any intermediate directories that don't exist; for instance,
mkdir -p foo/bar/baz
will create directories foo, foo/bar, and foo/bar/baz if they don't exist.
Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.
If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:
[ -d foo ] || mkdir foo
This should work:
$ mkdir -p dir
or:
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$dir already exists but is not a directory" 1>&2
fi
which will create the directory if it doesn't exist, but warn you if the name of the directory you're trying to create is already in use by something other than a directory.
Use the -p flag.
man mkdir
mkdir -p foo
Defining complex directory trees with one command
mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
If you don't want to show any error message:
[ -d newdir ] || mkdir newdir
If you want to show your own error message:
[ -d newdir ] && echo "Directory Exists" || mkdir newdir
mkdir foo works even if the directory exists.
To make it work only if the directory named "foo" does not exist, try using the -p flag.
Example:
mkdir -p foo
This will create the directory named "foo" only if it does not exist. :)
The old tried and true
mkdir /tmp/qq >/dev/null 2>&1
will do what you want with none of the race conditions many of the other solutions have.
Sometimes the simplest (and ugliest) solutions are the best.
Simple, silent and deadly:
mkdir -p /my/new/dir >/dev/null 2>&1
You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory.
dir=/home/dir_name
if [ ! -d $dir ]
then
mkdir $dir
else
echo "Directory exists"
fi
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
mkdir does not support -p switch anymore on Windows 8+ systems.
You can use this:
IF NOT EXIST dir_name MKDIR dir_name
directory_name = "foo"
if [ -d $directory_name ]
then
echo "Directory already exists"
else
mkdir $directory_name
fi
This is a simple function (Bash shell) which lets you create a directory if it doesn't exist.
#------------------------------------------#
# Create a directory if it does not exist. #
#------------------------------------------#
# Note the "-p" option in the mkdir #
# command which creates directories #
# recursively. #
#------------------------------------------#
createDirectory() {
mkdir -p -- "$1"
}
You can call the above function as:
createDirectory "$(mktemp -d dir-example.XXXXX)/fooDir/BarDir"
The above creates fooDir and BarDir if they don't exist. Note the "-p" option in the mkdir command which creates directories recursively.
Referring to man page man mkdir for option -p
-p, --parents
no error if existing, make parent directories as needed
which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn't exists before issuing this command
Correct Usage
mkdir -p /tmp/newdir/anotherdir
After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0). Due to this reason most people use this command in shell scripts before using those actual paths.
Or if you want to check for existence first:
if [[ ! -e /path/to/newdir ]]; then
mkdir /path/to/newdir
fi
-e is the exist test for KornShell.
You can also try googling a KornShell manual.
Improvement on the 'classic' solution (by Brian Campbell) - to handle the case of symlink to a directory.
[ -d foo/. ] || mkdir foo
mkdir -p sam
mkdir = Make Directory
-p = --parents
(no error if existing, make parent directories as needed)
if [ !-d $dirName ];then
if ! mkdir $dirName; then # Shorter version. Shell will complain if you put braces here though
echo "Can't make dir: $dirName"
fi
fi

Resources