2

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?

Yoo
  • 17,526
  • 6
  • 41
  • 47

3 Answers3

5
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
  • 68,372
  • 23
  • 116
  • 141
2

Have you tried:

cd "`xsel`"

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

dave
  • 11,641
  • 5
  • 47
  • 65
  • 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 Sep 01 '09 at 12:00
  • Bash will interpret a very small number of meta-characters inside double-quotes. Only single quotes stop all interpretation. – dave Sep 01 '09 at 21:04
0

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
  • 249,864
  • 45
  • 407
  • 398
  • If the directory is /egg/spam/chunky bacon/my music and if I type cd and paste the path, it's cd /egg/spam/chunky bacon/my music , which will cd into /egg/spam/chunky. – Yoo Sep 02 '09 at 06:49