SamAko
SamAko

Reputation: 3615

Going into directory using bash variable

I have the following functions in my ~/.bash_aliases file

mycd() {
  dir=$(cat)
  echo "$dir"
  cd "$dir"
}
alias c=mycd

and

gotoD() {
  find -name $1 -type $2 | awk '{ print $0 }' | sort -k2 | head -1 | c
}
alias goto=gotoD

I want to be able to type

goto directory_name d

and have the functions search for the directory and cd into the nearest one The problem is that though the found path to the directory gets into mycd, it is unable to actually change directories and simple remains in the same directory without any errors.

Any help would be greatly appreciated.

Thanks

Upvotes: 1

Views: 1789

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Set Proper Bash Option: cdable_vars

You're probably looking for the correct shopt option to set cdable_vars. The manual page says:

cdable_vars

If this is set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.

This simplifies your solution. For example:

shopt -s cdable_vars
goto=/etc
cd goto

Instead of assigning a static directory to goto, though, you could use a script, function, or pipeline to assign a directory name to goto.

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

Whenever you put a command into a pipeline, you force that command to be executed as a separate process. Since each process has it's own current directory, you only end up changing that one process's current directory and not the current directory of the shell you were typing in. Try implementing gotoD like this:

gotoD() {
  cd $(find -name $1 -type $2 | awk '{ print $0 }' | sort -k2 | head -1)
}

Now the logic of finding the proper directory is still executed in another process, but cd command is executed by the main process.

Upvotes: 3

Related Questions