0

I'm looking at some aliases to quickly save the current directory so it can be opened later.

ALIAS cdo='pwd|sed 's/ /\ /g' > ~/.cdo'
AIIAS cdn='cd "$(cat ~/.cdo)"'

The sed command obviously deals with spaces.

However, I still have a curious problem that I cannot fix that must involve variable interpretation.

jk@bt:~# cd Hello\ World/
jk@bt:~/Hello World# pwd|sed 's/ /\\ /g' > ~/.cdo
jk@bt:~/Hello World# cat ~/.cdo
/home/jk/Hello\ World
jk@bt:~/Hello World# cd ..
jk@bt:~# cd "$(cat ~/.cdo)"
bash: cd: /home/jk/Hello\ World: No such file or directory
james_kansas
  • 165
  • 2
  • 7
  • See http://mywiki.wooledge.org/BashFAQ/050 to understand why this behavior is happening: Quoted variable substitution (which is the right thing to use!) doesn't process escapes, nor should it. – Charles Duffy Jun 05 '12 at 15:30
  • It is much better to solve this problem with [`pushd, popd`](http://cli.learncodethehardway.org/book/cli-crash-coursech8.html) and `dirs` commands available in all flavors of Unix. – anubhava Jun 05 '12 at 15:31
  • Check out acd_func.sh -- extends bash's CD to keep, display and access history of visited directory names at http://geocities.com/h2428/petar/acd_func.htm – Tom Jun 05 '12 at 15:40

2 Answers2

2

Looks to me as if you're doubling the masking.

One way to handle spaces is to mask them individually with a backslash:

 cd here\ I\ go 

or to mask all of them with double quotes:

 cd "here I go" 

while this would be allowed as well:

 cd here" I "go

However, mixing them means, that you want literally backslashes:

 cd "here\ I\ go" 

and that's what's happening.

Note that while not very common, tabs and newlines can be included in files as well. Masking them works the same way, but reading them from a file might be different, and multiple blanks are often condensed by the shell to a single one.

user unknown
  • 35,537
  • 11
  • 75
  • 121
1

You have to escape with \ if the filename isn't between " and "

Escaping with cdo but not using " in cdn

ALIAS cdo='pwd|sed 's/ /\ /g' > ~/.cdo'
AIIAS cdn='cd $(cat ~/.cdo)'

Not escaping and using "" (I think this is better)

ALIAS cdo='pwd > ~/.cdo'
AIIAS cdn='cd "$(cat ~/.cdo)"'
Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63
  • The problem, rather, is that he *shouldn't* do manual escaping in contents which aren't going to be parsed. Your second example, then, is correct, but the explanation is misleading. – Charles Duffy Jun 05 '12 at 15:31