I have made a cli which computes the location of a certain directory, and I would really like to have the script change into it. My first approach was ./myscript | cd
which I've learned doesn't work as 1. cd
doesn't take piped arguments, and 2. the script won't be allowed to change the directory of the parent shell.
I learned that there are workarounds, and I tried creating a function in .bash_profile
:
function cdir(){
DIR=""
while read LINE; do
DIR=$LINE
done
echo $DIR
cd $DIR
}
Now running ./myscript | cdir
the correct directory is output, however, the directory is still not changed.
Using command substitution works: cd $(./myscript)
, but I'd really prefer to be able to write this using pipe. Do you have any idea how I can get this to work, or at least explain why it isn't possible?