Is it possible to write a bash function to change directory by passing the name of a directory variable?

I want write a function which changes the working directory by passing the name of a directory variable which has already been established like :

foo () { cd $"$1"
}

However when I try , for example, foo links I get -bash: cd: links: No such file or directory

Is it possible to do this ?

1

1 Answer

You can use variable indirection:

foo () { cd "${!1}"
}
dir=/mnt
foo dir
pwd # /mnt

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like