Search code examples
grepcd

Unable to cd into a grepped directory


I have a volume with spaces and periods that I am unable to cd into

bash-4.3$ ll /Volumes
total 8
drwxrwxrwt@  4 root       admin              136 Apr 17 11:08 .
drwxr-xr-x  33 root       wheel             1190 Feb  5 19:05 ..
lrwxr-xr-x   1 root       admin                1 Apr 17 09:41 Macintosh HD -> /
drwxr-xr-x   4 username   wheel   204 Jan 28 02:54 OS X 10.10.2 Update Combo

but trying to cd in this way yields

bash-4.3$ cd "$(ls /Volumes |grep 'OS X')"
bash: cd: OS X 10.10.2 Update Combo: No such file or directory

Solution

  • The problem, as indicated by RC in their comment is that the output from that command substitution is the bare directory name OS X 10.10.2 Update Combo which then is used as cd "OS X 10.10.2 Update Combo" but there is no such directory in the current directory. You would need cd /Volumes/"$(ls /Volumes |grep 'OS X')" to do what you wanted.

    That being said using ls and grep for this is not at all appropriate. A better solution is simply to use a glob.

    cd /Volumes/*"OS X"*
    

    This will fail (as would the original) if more than one directory/file matches the glob however.