bashlocate

Linux Command for locating/finding a file where the filename is stored in a variable


I know this should be simple command but I am not able to figure out the mistake. I think it something with the syntax

So I have a file name script.sh which is stored in a variable var1. So flow goes like this

#! /bin/bash
echo "Enter commit hash"
read commit
var1=`git diff-tree --no-commit-id --name-only -r "$commit"`
echo $var1
locate -br "$var1"

The code works fine till echo $var1, but I am not able to find/locate the path where file exisits.

Expected output

script.sh
/c/training

Assuming script.sh is present in /c/training.


Solution

  • Just in case, make sure to use name-only not name-oly

    See git diff-tree --name-only

    That would explain why var1 is empty.

    Also, use the suggestions from shellcheck for your bash script.

    #! /bin/bash
    echo "Enter commit hash"
    read -r commit
    var1=$(git diff-tree --no-commit-id --name-only -r "$commit")
    echo "$var1"
    locate -br "$var1"