Sudev Ambadi
Sudev Ambadi

Reputation: 655

A Shell script to find and cd into a folder taking a folder name as argument in one step

I tried writing a one liner in Bash,

find ~ -name Music -type d -exec cd '{}' \;

This one using find along with exec but I'm getting error:

find: `cd': No such file or directory

Second try with XARGS,

find ~ -name Music  -type d -print0 | xargs -0 cd  

Now again i tried to write a script .sh

pathe=$(find ~ -name $1 -type d | head -n 1 )
cd $pathe

And tried to execute the script ./1.sh Music ,and it didn't work.

Only thing that worked till now is by typing the below command directly into terminal

cd `find ~ -iname books -type d | head -n 1`

Can anyone help me out by pointing out my mistake ? I'm trying to write a one liner and to alias it later.

Note: The script didnt even work for find result with only one result and result without spaces.

I'm using konsole with bash version 4.2.45(2) .

Upvotes: 1

Views: 3052

Answers (2)

anishsane
anishsane

Reputation: 20970

There were some problems with first 3 implementations:

  1. -exec option expects an executable binary. cd is a shell builtin, not a binary, like /bin/bash
  2. xargs also takes executable binary.
  3. The code is correct. However, since you created a .sh file, & executed it, it got executed in a subshell. Thus, it created a subprocess (bash), found the directory, cd to that directory, & exited. Your current shell is un-affected.

There are 2 options to cd to the directory found:

1.Use subshell to change directory:

find ~ -name Music -type d -exec bash -c "cd '{}'; exec bash" \;

This starts a bash shell, & within that shell, it changes to the directory you want.
NOTE, that any changes you do will not be reflected in the parent shell.

2.Using bash function:

findAndCd(){
    pathe=$(find ~ -name $1 -type d | head -n 1 )
    cd $pathe
}

Usage:
findAndCd Music

Instead of cd, you may choose to use pushd instead. Personally, I don't like some command other than cd modifying my CWD & OLDCWD, without an easy way to restore both of them.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

You must run cd in your current shell. Running it in another shell won't work, as you've seen. Create a function. Example:

mycd (){
  cd "${1}foo"
}

Upvotes: 4

Related Questions