Unix - Create Path of Folders and File

Unix - create path of folders and file

Use && to combine two commands in one shell line:

COMMAND1 && COMMAND2
mkdir -p /my/other/path/here/ && touch /my/other/path/here/cpedthing.txt

Note: Previously I recommended usage of ; to separate the two commands but as pointed out by @trysis it's probably better to use && in most situations because in case COMMAND1 fails COMMAND2 won't be executed either. (Otherwise this might lead to issues you might not have been expecting.)

One command to create a directory and file inside it linux command


mkdir B && touch B/myfile.txt

Alternatively, create a function:

mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }

Execute it with 2 arguments: path to create and filename. Saying:

mkfile B/C/D myfile.txt

would create the file myfile.txt in the directory B/C/D.

In Unix, how to create a file in a absolute path name

In bash you should write:

path1="/home/folder"; echo "hello web" > $path1/foo

Or:

export path1="/home/folder"
echo "hello web" > $path1/foo

Notation you used works only in bash script.

Linux: copy and create destination dir if it does not exist


mkdir -p "$d" && cp file "$d"

(there's no such option for cp).

Unix command to make file and folders recursively


function mytouch { for x in "$@"; do mkdir -p -- `dirname -- "$item"` && touch -- "$x"; done }

usage:

mytouch aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt

$ ls -- aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt
--a/b/c/d.txt -a/b/c/d.txt aa/bb/cc/dd.txt

How to mkdir only if a directory does not already exist?

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

How to get full path of a file?

Use readlink:

readlink -f file.txt


Related Topics



Leave a reply



Submit