0

Is there a way to redirect output on Linux to a former argument. For example,

sort file.txt > file.txt

Would there be a way to avoid typing file.txt again?

3
  • The command you show wouldn't work anyway; it would simply truncate file.txt. Note that the shell handles the redirection, so file.txt is opened for writing (and truncated) before sort is ever invoked. – Jonathon Reinhart Dec 24 '14 at 1:48
  • Essentially a duplicate (which should be on superuser anyway): stackoverflow.com/questions/146435 – Jonathon Reinhart Dec 24 '14 at 1:51
  • I like that this truncates the file though. Seems like a quicker way to dump file contents than cat /dev/null > file.txt or at least an alternative. – jkeuhlen Dec 24 '14 at 1:57
1

For some commands, there may be some sort of option to avoid this kind of redundancy. But it is not the case generically for all commands in Linux.
In your case, the correct way to write what you already have is

sort file.txt -o file.txt

This will sort file.txt and write the results back to the same file.

If you want to save the argument so you don't have to keep typing a long file name, you could store it in a bash variable:

i="file.txt"; sort $i -o $i

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.