0

I was given a task to write script that works similar to "which" command in terminal. Here is what I already wrote:

#! /bin/bash
FILE=$1
for i in $PATH 
do 
if [[ "$i" -eq "FILE" ]] 
then 
echo …

Here I need to get a full path to a file that has been found. How could i get it? Thanks in advice.

Mak
  • 91
  • 9
  • 2
    Use [`realpath`](http://man7.org/linux/man-pages/man3/realpath.3.html). – Maroun Nov 20 '18 at 13:03
  • Link should be to the shell version: http://man7.org/linux/man-pages/man1/realpath.1.html. Or you can also use [`readlink -f`](http://man7.org/linux/man-pages/man1/readlink.1.html). – omajid Nov 20 '18 at 13:19
  • 2
    Your `for` loop is confused. The `PATH` variable contains a single string; to loop over the individual components, you have to split it on colons. Then you have to add the name of the file you are looking for to the end of each extracted directory. The resulting paths are typically (but not necessarily) already absolute. The `-eq` comparison operator is for numeric equality; use `=` for string comparison. And finally use `"$FILE"` with a dollar sign to examine your variable (but you should probably prefer lower case for your private variables). – tripleee Nov 20 '18 at 13:30
  • See also https://stackoverflow.com/questions/33469374/how-to-split-the-contents-of-path-into-distinct-lines – tripleee Nov 20 '18 at 13:42

1 Answers1

-1

If you're willing to use Python, use Terminal's locate program using subprocess, like:

import subprocess

def find_filepath(file_name):
    outcome = (subprocess.Popen(["locate", file_name], stdout=subprocess.PIPE).communicate()[0]).decode()
    return outcome.split("\n")

This should fetch a list of Absolute file path.

Random Nerd
  • 134
  • 1
  • 9
  • locate my find multiple files with the same name. It doesn't pick one based on the order of appearance in `$PATH` – omajid Nov 20 '18 at 13:17
  • I agree but what if there are multiple files with same name, hence to avoid ambiguity why not simultaneously check for duplicates as well, and then just slice out the one required based on index position (maybe even delete rest, as per need). – Random Nerd Nov 20 '18 at 13:20
  • You are right, but that's not how `PATH` or `which` work. The index of `locate` doesn't correspond to the one from searching `PATH` :/ – omajid Nov 20 '18 at 13:22
  • My answer was keeping in mind a bigger picture, but again you're right, as OP asked for something similar to `which`, so `realpath` should be a better and easier alternative. – Random Nerd Nov 20 '18 at 13:26