0

I have an example where I define a function named f which prints blah and then stores command itself and all its arguments into variable $@:

# f () { echo blah; "$@"; }
# df -h | f
blah
# df -h | f cat
blah
Filesystem                                              Size  Used Avail Use% Mounted on
rootfs                                                   37G   36G     0 100% /
udev                                                     10M     0   10M   0% /dev
tmpfs                                                   304M  308K  303M   1% /run
/dev/disk/by-uuid/466fbdef-029c-4625-8bb2-cde3acd77e55   37G   36G     0 100% /
tmpfs                                                   5.0M     0  5.0M   0% /run/lock
tmpfs                                                   2.1G     0  2.1G   0% /run/shm
/dev/sda2                                                74G  7.0G   63G  11% /home
/dev/sr1                                                5.6M  5.6M     0 100% /media
# 

How does this f cat part on the right of the pipe work? How does the stdout of df -h end up in the $@ variable? Why does cat print the content of the $@ variable?

1
  • 2
    "Why does cat print the content of the $@ variable?" cat is $@
    – muru
    Commented Jun 22, 2015 at 1:37

1 Answer 1

3

In:

df -h | f

You redirected df -h output to f standard in, then called f without any arguments, $@ is empty.

In other hand:

df -h | f cat

You redirected df -h output to f standard in, then called f with one argument cat. "$@" inside f expanded to cat. cat concatenated standard in, which is df -h output, to standard out.

2
  • I see, thanks! So basically in case of df -h | f cat after executing df -h part a new subshell is made and f function/command is executed which has cat as its only argument? In addition, how did the output of df -h "survive" up to cat command when before the cat there was echo blah? I mean echo a | echo b; cat obviously does not print a.
    – Martin
    Commented Jun 22, 2015 at 11:24
  • @Martin: In echo a | echo b; cat, cat is not part of pipeline. You need group command to do that. Try echo a | {echo b; cat;}
    – cuonglm
    Commented Jun 22, 2015 at 14:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .