0

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)

6
$ 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 right – Tolga Varol Jul 25 '15 at 0:15
  • That is correct. – PSkocik Jul 25 '15 at 0:18
  • 1
    @Winny - something like that – mikeserv Jul 25 '15 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 cat is not in any way involved, please? – mikeserv Jul 25 '15 at 0:38
  • 1
    I'd have used "for i; do ... stuff with $i; done" for looping over the arguments rather than while/shift. – Random832 Jul 25 '15 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.