I know saying this may have me looked down upon, but this question is for homework from my UNIX class. While in my home directory, I am supposed to display all files in the /dev directory that begin with "sda". I can easily accomplish this by typing the command ls /dev | grep ^sda, which results in the desired output of "sda, sda1, sda2, ...".
Now I am trying to replicate this output without using pipe, so I type the command ls /dev ; grep ^sda, which outputs every file in the directory instead of only the ones that start with sda.
Any help is much appreciated, thank you.
CodePudding user response:
The command to list all files in /dev
starting with sda
without a pipe and grep is
ls /dev/sda*
Here the asterisk is a shell globbing character meaning any sequence of characters, including none. It might output, for example,
/dev/sda /dev/sda1 /dev/sda2
There are other ways to glob filenames in the shell, namely
?
representing exactly one character[a-z]
representing ranges of a single character
Try
ls /dev/sda[321xyz]
ls /dev/sd?
ls /dev/sd?[1-5]
ls /d[d-f]?/sd*
CodePudding user response:
Semicolons are command separators. That means that each command is run, one before the next, and the output goes to the terminal. There are other command separators like && and ||. These will only run the next command in the sequence if the first succeeds (&&) or fails (||).
The pipe operator, on the other hand, connects the output of one command to the input of another. In your example, the output of ls
(a list of files) is provided as input to grep
. The two commanda are actually running at the same time, with output from the first immediately going in as input to the second.
You get different results, then, because you are doing fundamentally different things.
ls /dev | grep ^sda
Takes the output of ls and only returns entries that start with "sda". Meanwhile,
ls /dev ; grep ^sda
Runs ls to completion, listing all files in /dev. And then it runs grep. Grep actually waits for you to type something since it has nothing connected to its input stream.