[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash: pipe once more



Stefan Schmidt wrote:
Hello,

if I pipe the output of a cd command the working directory doesn't change.

,----
| $ cd ~/bin 2>&1 | tee -a output.log; pwd
| /home/stefan
`----

How come and how can I get this to work?

Stefan



'cd' is a shell "builtin" command. In 'bash' and 'ksh', you can redefine what a builtin does, using a function, and a special command name the shell recognizes that forces it to use the builtin.

For bash, the command is 'builtin', for ksh it's 'command'.

So:

function cd
{
  pwd
  builtin cd $1   # bash
  # command cd $1 # ksh
  pwd
}

Now, when you run 'cd', the shell runs the function version you defined, does whatever you ask, runs the "real" (or "builtin") version of the cd command, so the current shell working directory is changed, does what ever else you ask, and exits. So, you can have the function test the destination, generate a custom error, redirected to 'tee' or to a file, and so on.

Leaving you in the new directory. The above sample has been tested with both the mentioned shells. I expect other shells would have similar features.

BE CAREFUL!! These functions become recursive if you fail to use the proper "special" command, and will eat up all your system resources, memory, etc., while they run. Fortunately, this condition is caught fairly quickly and the shell either terminates or the function does.

--
Bob McGowan

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature


Reply to: