LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   tcsh: pushd + popd in one function (https://www.linuxquestions.org/questions/programming-9/tcsh-pushd-popd-in-one-function-817888/)

lucmove 07-03-2010 06:01 PM

tcsh: pushd + popd in one function
 
I really like pushd and popd, but I don't like their long spellings, so I made aliases: 'x' runs pushd and 'xx' runs popd. That's not bad, but I wish I could improve them in the following way:

x => If followed by a path, 'pushd' (and cd to) that path. If not given any arguments, run 'popd'.

xx => 'cd -'

The problem is implementing that pushd/popd in one command trick. Since tcsh does not have functions, I've been struggling hard to come with a solution. I made a script, and it works, but it only works within the context of the script. The script exits and not only am I still sitting in the same directory, but also my dirstack is emptied.

A similar problem: make 'cdd'. I remember using that program in DOS a long time ago. I would run 'cdd /path/to/directory' and cd to that path if it existed, or create it and cd to it if it didn't exist. Again, I made a script, but that only works within the context of the script, not my current shell. So the new dir is created, but my shell won't cd into it.

Help, please?

lucmove 07-03-2010 06:56 PM

Solved
 
Ok, I found the solution on my own. I was making the following mistake in my .tcshrc:

Code:

foreach i (`\ls -1 ~/myscripts`)
        eval alias `basename "$i" .sh` "~/myscripts/$i"
end

That was causing each script to be executed as a command. The right (and rather arcane!) way to make it work is to use 'source':

Code:

foreach i (`\ls -1 ~/myscripts`)
        eval alias `basename "$i" .sh` "source ~/myscripts/$i"
end

Now it works. And here is the complete solution in case someone ever wants to use the idea:

in .tcshrc:
Code:

foreach i (`\ls -1 ~/myscripts`)
        eval alias `basename "$i" .sh` "source ~/myscripts/$i"
end

# or just make one specific alias:
# alias x "source ~/myscripts/x.sh"

alias xx 'cd - '

in ~/myscripts/x.sh:

Code:

#!/usr/bin/env tcsh

if        ( $#argv < 1 ) then
        popd
        exit
endif

if        ( -e "$1" ) then
        pushd "$1"
else
        echo "$1 not found."
endif

Note: I like the whole idea better with this line in .tcshrc:

Code:

alias cd 'pushd '
And a little bit of complete magic:

Code:

complete {cd,popd,pushd,x}        'n/*/d/'


All times are GMT -5. The time now is 06:12 PM.