Baruch
Baruch

Reputation: 21548

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/

Upvotes: 29

Views: 21763

Answers (4)

jordanm
jordanm

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

shock_one
shock_one

Reputation: 5925

echo "something" | install -D /dev/stdin $f

Upvotes: 13

dogbane
dogbane

Reputation: 274878

You can use mkdir -p to create the folder before writing to the file:

mkdir -p "$(dirname $f)"

Upvotes: 4

Alex Gitelman
Alex Gitelman

Reputation: 24732

try

mkdir -p `dirname $f` && echo "something" > $f

Upvotes: 7

Related Questions