1

I've noticed sometimes I touch a file that does not exist at all and after the command, the files get created. However, depending on what directory I'm touching, I get "No such file or directory" error.

For example, If I run touch foo.txt, the foo.txt file gets created in my home directory. Instead, if I run touch /bar/foo.txt, I get touch: cannot touch '/bar/foo.txt': No such file or directory.

What's the logic behind this? Thanks.

jgam
  • 11

2 Answers2

0

The touch command doesn't need the target file to exist, but it needs the parent directory of the target file to exist. So if you want to run touch /bar/foo.txt then you need to make sure that the /bar/ directory already exists.

The touch command (like most command-line programs) also assumes that the path argument that you give it is a relative path. So touch foo.txt will create a file in your current working directory. If your current directory happens to be your home directory then foo.txt will be created in your home directory.

igal
  • 9,886
0

You are getting "No such file or directory" error because /bar/foo.txt is looking in root/bar/foo.txt. From your home directory try "bar/foo.txt" (not /bar/foo.txt). Assuming that bar directory exists in your home directory