First of all I'm very new to shell scripting. But I'm starting to love it more and more.
I really enjoy working on the Terminal, which why I started looking into customizing it for my needs by creating a personal prompt. You know, pro devs - pro prompts :-P
I'm pretty much satisfied with it at the moment. It has all the basic information that you would expect a prompt to have.
But I would love to add a non-standard "feature" to my prompt, but my newbieness is kicking my ass.
What I would love to do, is to create a method which looks for a specific file - in my case
I am kind of confused ... you say you are searching for
composer.json but are talking about
composer.lock ??? So below I will give you a script that finds composer.lock, you can change the
file-variable at the beginning of the script if you want to change which file you're looking for!
I assumed your command
composer show -i | grep "laravel/framework" would work in any directory the file composer.lock is found as you said in your comment.
So if it has to be done without changing the current directory, there are 2 options:
The cleanest way: push the current directory to the stack with
pushd and before exiting pop the directory back with
popd. Based on this website we shouldn't call pushd without argument
One difference is the way pushd is handled if no arguments are given. As in csh, this exchanges the top two elements of the directory stack
You could then try this:
file=composer.lock unset failure # pushd actually current directory and change to current directory pushd . while [ ! -f "$file" ] do if [ "$(pwd)" != "/" ] then cd .. else failure=true break fi done if [ -z "$failure" ] then echo Found file in $(pwd) # Your command! composer show -i | grep "laravel/framework" popd else echo File $file could not be found! >&2 popd exit 1 fi exit 0
The other option is to hold a variable that holds the directory we've reached so far. This will allow to search for the file without changing directory at all!
file=composer.lock unset failure cpath=$(pwd) while [ ! -f "$cpath/$file" ] do if [ "$cpath" != "/" ] then cpath=$(cd $cpath/.. && pwd) else failure=true break fi done if [ -z "$failure" ] then echo Found file in: $cpath # do something with $cpath ... else echo File $file could not be found! >&2 exit 1 fi exit 0
It works in
bash. As I don't have a
zsh installed, I couldn't try it out in
zsh but I think it should work there too. I'm not sure though
You can leave out the
echo Found file in $(pwd) if you want to. I had it there for test purposes