slashlos slashlos - 2 months ago 5x
Bash Question

alias shell variable dereference

I move about a lot in paths, and trying to use an alias set to minimize typing:

alias restore 'set restore=\!*; cd \$${restore}'
alias save 'setenv \!* `pwd`'

I'm using tcsh; the save works but the restore fails:

2% save x
2% cd
2% restore x
$x: No such file or directory.

I inspect the var (x) and it's fine so I'm not dereferencing right?


This works:

alias restore ' cd ` echo $\!* ` '

Your original attempt can be better written as:

alias restore ' cd \$\!* '

This (and your original one) doesn't work because variable expansion needs to happen first, and in this case there is no variable expansion, because $ is escaped. After !* is expanded, there isn't another variable expansion happening.

In my proposed solution I avoid escaping $ by running a echo in a sub-shell, so it works fine.

Just to make sure, you are aware of pushd and popd, right? For most users, those are useful and powerful enough, though I can certainly see the value in your aliases here.