0

I'm new to Bash and I'm trying to learn how to firstly execute two commands using the | symbol, and secondly how to join two commands into a compound command.

When writing two commands in one line the pipeline symbol | is meant to connect the output of the first command to the input of the second. So I don't quite understand how it fails to join "Hey" and ", how are you?".

    echo "hey" | echo ", how are you?" 

When writing a compound command, commands should be between the opening and closing braces separated by a semicolon. In this case

    { echo "Hey"; echo ", how are you" }

, but it doesn't seem to work as expected.

What could I be missing out here, for these two cases?

MarkoCrush
  • 67
  • 8
  • 1
    It is difficult to offer solutions when the problem statement is simply, "it doesn't work". Please [edit] your question to give a more complete description of what you expected to happen and how that differs from the actual results. See [ask] for hints on what makes a good explanation. – Toby Speight Nov 02 '16 at 17:10
  • 1
    You can't just chain arbitrary commands together with `|`; [piping](http://stackoverflow.com/q/9834086/113632) is a tool specifically for sending the output of one program into the input of a second program. If the second program isn't designed to handle that input you're just writing gibberish. – dimo414 Nov 02 '16 at 17:34
  • dimo414 learn to control your temper – MarkoCrush Nov 04 '16 at 01:53

1 Answers1

5

Short version: use printf instead of echo.


echo does not read from its standard input, so the pipe is effectively the same as

echo "hey"; echo ", how are you?"

which are two separate commands, each of which prints an implicit newline after the last argument.

Your brace command fails because a semicolon or newline is required after the last command: { echo "Hey"; echo ", how are you"; }.

The answer to your question, though, is that you need to suppress the newline that echo prints.

echo -n "hey"; echo ", how are you?"

This will work for bash, but not all shells, as the -n option is non-standard. printf is more reliable:

printf "hey"; printf ", how are you?\n"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • One thing to mention with `printf`: it's more robust to write `printf '%s' "$text"` when there might be a `%` in the text (not the case in the mcve, but can be an issue in real code). – Toby Speight Nov 02 '16 at 17:09