1

I'm trying to make a shell function that looks for a file existence in the current dir. If the file doesn't exists if the current dir, it should try the parent dir, and go up to the root of the filesystem (going up to ~ should be more than enough).

What I'm trying to achieve is display the current ruby on rails version used for a project on my prompt. The easy way is to call bundle show rails and parse the string, but it is quite slow; so I want to parse the file that contains the versions informations, Gemfile.lock. What I have currently only works when I'm in the root of the project (where the Gemfile.lock lives).

This could also be used to parse a git config file, though git config is pretty fast.

Thanks for your time

ksol
  • 11,835
  • 5
  • 37
  • 64

2 Answers2

2

like this?

#!/bin/zsh

# the function    
findfile_parent() {
 FILE=$1
 while [ ! -e "${FILE}" ]; do
  if [ "$(pwd)" = "/" ]; then
    return
  fi
  cd ..
 done
 echo "$(pwd)/${FILE}"
}

# usage example
SEARCHFILE=foo.pyl
UPFILE=$(findfile_parent ${SEARCHFILE})
if [ "x${UPFILE}" != "x" ]; then
 echo "found file ${SEARCHFILE} as ${UPFILE}"
else
 echo "couldn't find file ${SEARCHFILE}"
fi
umläute
  • 28,885
  • 9
  • 68
  • 122
0

Refer the below two helpful links to find out your solution.

Get parent directory of current directory in Ruby

How to check for file existence

):

Community
  • 1
  • 1
Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85