a simple question, can I create a file at a location I want & using cat command & without using pipes & and the location is some other place than I where I am currently. (I would appreciate an edit)
1 Answer
$ cat > location/i/want/theFileImCreating
cat doesn't really create files. It just writes to its standard output. In the above command, it's the output redirection (>) (set up by the shell) that creates the file (or empties an already existing one).
By default, redirections (>) clobber the target if it exists. If you want to prevent that, set -o noclobber is your friend.
If you don't want to fill the file with anything, touch will create a new empty file (or update the timestamp on an existing one).
If you want to strictly "create" a new file, including its path, a helper shell function/script might come in handy:
fcreat(){
while (( "$#" )); do
[ ! -f "$1" ] && {
mkdir -p "$(dirname "$1")";
touch "$1";
}; shift
done
}
Usage:
$ fcreat location1/i/want/file1 location2/i/want/file2
$ tree
$ tree
.
├── location1
│ └── i
│ └── want
│ └── file1
└── location2
└── i
└── want
└── file2
fcreat: I don't know if I'm becoming a Unix expert or if I'm just losing my ability to spell.
-
Thanks, location must exist though, cat can't create a directory rightTolga Varol– Tolga Varol2015-07-25 00:15:46 +00:00Commented Jul 25, 2015 at 0:15
-
That is correct.Petr Skocik– Petr Skocik2015-07-25 00:18:04 +00:00Commented Jul 25, 2015 at 0:18
-
1@Winny - something like thatmikeserv– mikeserv2015-07-25 00:38:17 +00:00Commented Jul 25, 2015 at 0:38
-
1@PSkocik - thank you. mine was screwed up. Yours is better. But can you do me a favor? I think theres a basic misunderstanding about who is responsible for the pathname creation. Just make it clear that
catis not in any way involved, please?mikeserv– mikeserv2015-07-25 00:38:52 +00:00Commented Jul 25, 2015 at 0:38 -
1I'd have used "for i; do ... stuff with $i; done" for looping over the arguments rather than while/shift.Random832– Random8322015-07-25 05:38:08 +00:00Commented Jul 25, 2015 at 5:38