8

Please consider this simple script named test:

#!/bin/bash
echo $1

and the following commands and calls:

$ echo "A B"
A B
$ echo ""A B""
A B
$ echo """A B"""
A B
$ echo """A B"""
A B

$ ./test "A B"
A B
$ ./test ""A B""
A
$ ./test """A B"""
A B
$ ./test """"A B""""
A

Could someone please explain why the call of test doens't behave like the command echo or point to the relevant documentation?

  • 2
    There is already a test command, you are lucky you were using the full path, otherwise you would have had a tough time debugging the situation. – Rui F Ribeiro Dec 8 '15 at 16:34
  • 3
    Better for this kind of test is to use printf '%q\n' "$@" instead of echo at all, which will emit your arguments one-to-a-line with hidden characters and whitespace escaped in a visible form. – Charles Duffy Dec 8 '15 at 17:24
13

Because echo concatenates all it arguments to print them, and your script is limited to the first argument. You should use "$@" and not $1 in your script.

Let's look at the arguments you're providing for your tests:

  • ./test "A B"
    • one argument, the 3 character string AspaceB
  • ./test ""A B""
    • two arguments
      • first, empty string concatenated with A
      • second, B concatenated with empty string
  • ./test """A B"""
    • one argument, empty string concatenated with AspaceB concatenated with empty string
  • ./test """"A B""""
    • two arguments
      • first, empty string concatenated with empty string concatenated with A
      • second, B concatenated with empty string concatenated with empty string

Note: you would see different results from echo if you had used more than one space in your arguments. That's because echo concatenates its arguments with a single space:

$ echo "A   B"
A   B
$ echo ""A   B""
A B
$ echo """A   B"""
A   B
$ echo """"A   B""""
A B
  • those are neat little empty string doodads. – mikeserv Dec 8 '15 at 16:28
  • 2
    exactly, quotes don't nest... – mr.spuratic Dec 8 '15 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.