I know you can do mkdir
to create a directory and touch
to create a file, but is there no way to do both operations in one go?
i.e. if I wa
no need for if then
statements...
you can do it on a single line usign ;
mkdir -p /my/other/path/here;cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
-- or on two lines --
mkdir -p /my/other/path/here
cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
-- the -p
prevents error returns if the directory already exists (which is what I came here looking for :))
In the special (but not uncommon) case where you are trying to recreate the same directory hierarchy, cp --parents
can be useful.
For example if /my/long
contains the source files, and my/other
already exists, you can do this:
cd /my/long
cp --parents path/here/thing.txt /my/other
as I saw and test in a unix forum this solves the problem
ptouch() {
for p in "$@"; do
_dir="$(dirname -- "$p")"
[ -d "$_dir" ] || mkdir -p -- "$_dir"
touch -- "$p"
done
}
You need to make all of the parent directories first.
FILE=./base/data/sounds/effects/camera_click.ogg
mkdir -p "$(dirname "$FILE")" && touch "$FILE"
If you want to get creative, you can make a function:
mktouch() {
if [ $# -lt 1 ]; then
echo "Missing argument";
return 1;
fi
for f in "$@"; do
mkdir -p -- "$(dirname -- "$f")"
touch -- "$f"
done
}
And then use it like any other command:
mktouch ./base/data/sounds/effects/camera_click.ogg ./some/other/file
if you want simple with only 1 param snippet :
rm -rf /abs/path/to/file; #prevent cases when old file was a folder
mkdir -p /abs/path/to/file; #make it fist as a dir
rm -rf /abs/path/to/file; #remove the leaf of the dir preserving parents
touch /abs/path/to/file; #create the actual file