0

I want to find a file and goto his directory. I made a bash script :

#!/bin/bash

FILE=$1
FILEPATH=`find . -name "$FILE"`

if [ -f "$FILEPATH" ]
then
    cd $(dirname "$FILEPATH")
fi

But this script does not work. I saw on this post that I have to add exec bash or $SHELL but it create a new bash prompt ans display my welcome message.

How can I do ? I just want a script, alias or something to find a file and go to the directory containing that file.

A.Pissicat
  • 3,023
  • 4
  • 38
  • 93
  • 2
    Do not use the `PATH` as an ordinary variable. Change your own variables to lower case letters. By convention, capitalized variables are environment variables and shell internal variables. – M. Nejat Aydin Feb 18 '21 at 10:13
  • 1
    @M.NejatAydin I changed the name, thank you – A.Pissicat Feb 18 '21 at 10:21

1 Answers1

2

Source your script instead of running it like you do. When you run it like you do, you spawn a new shell that executes the cd, completes succesfully, closes the shell and returns to your current shell, leaving you in your pwd.

Use source myscript.sh or . myscript.sh instead of bash myscript.sh or myscript.sh.

Pallie
  • 965
  • 5
  • 10