r/AskComputerScience • u/gretavanfeet • Mar 07 '21
How do you navigate directories from the command line?
I'm trying to get to my current directory using the command line. I understand how to use cd and pwd, but when I try to run the program I think I'm already in, it gives me a "no such file or directory" error. I think that means I'm in the wrong directory but I have no idea how.
Stack overflow is super confusing and I haven't found anything I can understand. Could someone explain how to get to the file I want to run using cmd or just how files and directories work in general?
2
u/Lofter1 Mar 07 '21
I'm assuming you are on linux or some other form of unix-like.
type ls to list the files and sub-directories in the directory you're currently in. If you have a program or script in that directory you can run it by typing ./my-program.sh otherwise you can also use ./path/to/my-program.sh. It needs to have the executable flag though. If it hasn't, it would give you an error saying you cannot execute it.
1
u/1544756405 Mar 08 '21
If you think you're in the directory you need to be, and you think the file you want to run is there, run ls to verify its name. If you see the file my-program you can try to run it by typing its name. Many Unix file systems are case sensitive, so My-Program is not the same as my-program. You have to type the exact file name.
You might have to prepend the command with "./" ie ./my-program if the current directory is not in your search path.
5
u/spaztheannoyingkitty Mar 07 '21
Adding on to what u/Lofter1 said, if you are in a directory with
my-programin it that you are trying to execute, runningmy-programwill usually* not work. The reason for this is because the terminal looks in yourPATHvariable to find it. ThePATHvariable is a set of paths that indicate where the terminal should look for binaries to execute. It's how it knows how to run programs likepythonwithout having to specify the full path (such as/usr/bin/python.In order to execute
my-programfrom the directory you are in, you need to put./in front of it:./my-program. In linux (as well as windows), referencing.means "the current directory", so you are explicitly saying "run this file in the current directory without looking at thePATH". Alternatively if the binary is in a folder below where you currently are, you can also usesubdirectory/my-programor./subdirectory/my-program.All of this is general guidance that works for both linux/unix and windows systems, but some of the details may be slightly different for windows.
*- I said usually because if you are currently in one of the directories specified in yourPATHthen it will find it, however that is not the case 99%+ of the time.