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

96 Views Asked by At

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.

2

There are 2 best solutions below

5
VonC On BEST ANSWER

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"
1
Helium On

Tried using the find command instead of locate after reading up on the difference between the two. Works now.