BASH redirect create folder - bash

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)"

Related

Send files to folders using bash script

I want to copy the functionality of a windows program called files2folder, which basically lets you right-click a bunch of files and send them to their own individual folders.
So
1.mkv 2.png 3.doc
gets put into directories called
1 2 3
I have got it to work using this script but it throws out errors sometimes while still accomplishing what I want
#!/bin/bash
ls > list.txt
sed -i '/list.txt/d' ./list.txt
sed 's/.$//;s/.$//;s/.$//;s/.$//' ./list.txt > list2.txt
for i in $(cat list2.txt); do
mkdir $i
mv $i.* ./$i
done
rm *.txt
is there a better way of doing this? Thanks
EDIT: My script failed with real world filenames as they contained more than one . so I had to use a different sed command which makes it work. this is an example filename I'm working with
Captain.America.The.First.Avenger.2011.INTERNAL.2160p.UHD.BluRay.X265-IAMABLE
I guess you are getting errors on . and .. so change your call to ls to:
ls -A > list.txt
-A List all entries except for . and ... Always set for the super-user.
You don't have to create a file to achieve the same result, just assign the output of your ls command to a variable. Doing something like this:
files=`ls -A`
for file in $files; do
echo $file
done
You can also check if the resource is a file or directory like this:
files=`ls -A`
for res in $files; do
if [[ -d $res ]];
then
echo "$res is a folder"
fi
done
This script will do what you ask for:
files2folder:
#!/usr/bin/env sh
for file; do
dir="${file%.*}"
{ ! [ -f "$file" ] || [ "$file" = "$dir" ]; } && continue
echo mkdir -p -- "$dir"
echo mv -n -- "$file" "$dir/"
done
Example directory/files structure:
ls -1 dir/*.jar
dir/paper-279.jar
dir/paper.jar
Running the script above:
chmod +x ./files2folder
./files2folder dir/*.jar
Output:
mkdir -p -- dir/paper-279
mv -n -- dir/paper-279.jar dir/paper-279/
mkdir -p -- dir/paper
mv -n -- dir/paper.jar dir/paper/
To make it actually create the directories and move the files, remove all echo

Can I recursively create files on Bash?

If I run touch non/existing/folder/my-file.txt, touch complains about non-existing folders.
Can I create these folders on the same command, similar to mkdir -p?
No, but you can write a script that does that:
# new.sh
for file; do
[[ $file =~ ((.+\/)*)(.+) ]] && mkdir -p "${BASH_REMATCH[2]}"
touch $file
done
Then run: ./new.sh non/existing/folder/my-file.txt possibly/other/files.txt

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.

Only mkdir if it does not exist [duplicate]

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

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