简体   繁体   中英

> and < difference Bash

I have to test if pathname is a regular file and if it's length is greater 50 bytes , for this reason I do like this:

if [[ -f $path && `wc -c < $path` -gt 50 ]]; then ......

and it works , but , for curiosity , I tried to do also like this:

if [[ -f $path && `$path > wc -c` -gt 50 ]]; then ......

but it doesn't work and I don't understand why.

For this reason I ask you the difference between < and > operator in Bash.

< is "read from" -- redirecting input, while > is "write to" -- redirecting output. Both are followed by the name of the file to use. So

wc -c < $path

runs the wc command, reading from the file $path

$path > wc -c

runs the $path command, writing to the file wc

These operators are not commutative (position aren't swappable).

wc -c < $path means launch wc and use the file at $path as the input.

$path > wc -c means launch the executable at $path (which in your case $path isn't an executable) and send it's output to the file at wc .

As you can see the second one doesn't really make sense. Always make the executable the first operand (argument), and the file you are reading from or writing to the second operand.

< instructs the shell to take the contents of the file on the right side of the operator and provide them as input to the command on the left side.

> instructs the shell to take the output of the command on the left side and store it in the file named on the right side.

Accordingly, the command wc -c < $path is equivalent to cat $path | wc -c cat $path | wc -c . $path > wc -c would mean "run the command $path and store the output in a file named wc (the -c would be discarded)."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM