0

Is it possible to pipe cd commands?

For example, I want to go into a directory and then use a file command on it's contents but when I type cd x | file * it just does the file command on my current directory and it doesn't change directory at all.

2
  • 1
    what shell are you using? if its bash just replace the pipe with &&, or a semicolon if you don;t care to validate that the cd worked before running the file command. cd doesn't really produce output, so its not really useful to use it with pipes or redirections. your file statment should probably change to file .\* – Frank Thomas Jun 18 at 4:21
  • 1
    This question is not possible to answer without knowing what shell you are using. – DavidPostill Jun 18 at 7:43
3

A pipeline takes the output of one command and uses it as the input to another command.  So there are two problems with what you tried.

  1. The cd command doesn’t produce any output1.
  2. file * doesn’t take any input.  You might say, “Of course it takes input; it reads (part of) all the files.”  But it doesn’t read standard input.  If you type file *, it just runs and gives you its output; it doesn’t read anything from the keyboard.

What you want is cd x; file *, to do the cd and then the file *.

As you may realize, that command line will leave you in directory x.  So an alternative is

(cd x; file *)

which runs the cd and the file in a subshell.  The working directory of you main shell won’t change.  A drawback of that is that, if the command line sets any shell variables or otherwise changes the shell’s state, that will also affect only the subshell and not the main shell.

________________
1 Well, sometimes it outputs the directory name.

3
  • it really depends on which shell the OP is using, because in cmd () doesn't start a subshell at all, and in powershell it's just used for grouping expressions – phuclv Jun 18 at 9:29
  • (1) AFAICT, there is no file command natively in CMD or PowerShell, so the question is obviously about Unix-like systems.  Is there any shell on a Unix-like system where my answer is wrong?  (2) Your comment, while not (strictly) wrong, is somewhat misleading — parentheses are used for grouping in CMD also. – Scott Jun 18 at 17:20
  • it's entirely possible to install GNU file or any POSIX tools on Windows. And yes, I know () groups commands in cmd but it doesn't create a subshell – phuclv Jun 19 at 2:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.