1

That script test.sh doesn't work after used pipe command. The result shows nothing. Why?

#!/bin/bash

fun=$( echo $1 )
echo "$fun"

commands are as follows,

$ echo 1 | ./test.sh
3
  • There is nothing special about that script...
    – jasonwryan
    Nov 28, 2014 at 0:15
  • 5
    Your script doesn't do anything with the piped input: you seem to be confusing a script's positional parameters with its standard streams Nov 28, 2014 at 0:15
  • @steeldriver I think it should output '1'. But it shows nothing.
    – Yunong
    Nov 28, 2014 at 0:18

2 Answers 2

2

steeldriver is correct. What you should do is either:

  1. Use a command that reads in the standard input:

    #!/bin/bash
    
    fun=$(cat)
    echo "$fun"  
    

    Or simply:

    #!/bin/bash
    
    cat
    
  2. Or, to convert standard input into positional parameters, use xargs:

    $ echo 1 | xargs ./test.sh
    
  3. Or, use the script the way it is supposed to be used (as coded):

    ./test.sh 1
    
0
0

Do this instead

#!/bin/bash
echo "$@"

Then run it like this

./test.sh 1

It will echo 1, don't make it too complicated. And besides, why not just use echo? There is no reason to use this script.

2
  • It still doesn't work.
    – Yunong
    Nov 28, 2014 at 0:36
  • The reason why i use this script is that I found that error in another script, so I just try to explain that problem in a simple way.
    – Yunong
    Nov 28, 2014 at 0:40

You must log in to answer this question.

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