Reputation: 21548
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/
Upvotes: 29
Views: 21763
Reputation: 35014
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"
Upvotes: 26
Reputation: 274878
You can use mkdir -p
to create the folder before writing to the file:
mkdir -p "$(dirname $f)"
Upvotes: 4