views:

115

answers:

3

Is there a way to do command substitution in BASH shell without breaking output into multiple arguments?

I copy the path of some directory (from the location bar in a GUI file browser) to clipboard and then issue the following command, where the command xsel returns the clipboard content, which is the path of the directory in this case:

cd `xsel`

But some path contain spaces or may even contain some special characters used by BASH.

How can I pass the output of a command as a single argument and without BASH messing with special characters?

+2  A: 

Have you tried:

cd "`xsel`"

That should do the job, unless you have dollars($) or back-slashes (\) in your path.

dave
I don't think it matters whether you have meta-characters in the string once you've wrapped the `xsel` in double-quotes
Adrian Pronk
Bash will interpret a very small number of meta-characters inside double-quotes. Only single quotes stop all interpretation.
dave
A: 

If you aren't doing this programmatically, most terminals in Linux let you paste from the clipboard with a middle-click on your mouse. Of course, you'll still need to put quotes before and after your paste, like @dave suggests.

Mark Rushakoff
If the directory is/egg/spam/chunky bacon/my musicand if I type cd and paste the path, it'scd /egg/spam/chunky bacon/my music, which will cd into /egg/spam/chunky.
RamyenHead
+5  A: 
cd "$(xsel)"

seems to handle all special characters (including $ and spaces).

My test string was boo*;cd.*($\: $_

$ mkdir "$(xsel)"
$ ls
boo*;cd.*($\: $_

$ file boo\*\;cd.\*\(\$\\\:\ \$_/
boo*;cd.*($\: $_/: directory

$ cd "$(xsel)"
$ pwd
/tmp/boo*;cd.*($\: $_
ire_and_curses