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.

4
  • 2
    Use realpath.
    – Maroun
    Commented Nov 20, 2018 at 13:03
  • Link should be to the shell version: man7.org/linux/man-pages/man1/realpath.1.html. Or you can also use readlink -f.
    – omajid
    Commented Nov 20, 2018 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
    Commented Nov 20, 2018 at 13:30
  • See also stackoverflow.com/questions/33469374/…
    – tripleee
    Commented Nov 20, 2018 at 13:42

1 Answer 1

-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.

4
  • locate my find multiple files with the same name. It doesn't pick one based on the order of appearance in $PATH
    – omajid
    Commented Nov 20, 2018 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). Commented Nov 20, 2018 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
    Commented Nov 20, 2018 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. Commented Nov 20, 2018 at 13:26

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