bash - Write to a file whose path does not exist yet -


i want write file file.txt using terminal in

/dir1/dir2/dir3/dir4...dirn/file.txt 

the path /dir1/dir2/dir3/dir4...dirn/ not exist. how can write file path gets created on fly?

just use mkdir -p ths:

mkdir -p /dir1/dir2/dir3/dir4...dirn/ 

the -p creates whole directory structure if not exist. explained in mkdir man page:

create intermediate directories required. if option not specified, full path prefix of each operand must exist. on other hand, option specified, no error reported if directory given operand exists. intermediate directories created permission bits of rwxrwxrwx (0777) modified current umask, plus write , search permission owner.

and here used in 1 small shell script; going /dir1/dir2/dir3/dir4/ example:

if [ ! -d /dir1/dir2/dir3/dir4/ ];   mkdir -p /dir1/dir2/dir3/dir4/; fi; echo "hello world" >> /dir1/dir2/dir3/dir4/file.txt 

or make bit more flexible, can add variables & use dirname file basepath:

// set filename. filename="/dir1/dir2/dir3/dir4/file.txt"  // directory basepath using dirname. directory=$(dirname ${filename})  // if directory not exist, create it. if [ ! -d ${directory} ];   mkdir -p ${directory}; fi  // appending text filename in directory. echo "hello world" >>  ${filename} 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -