1

The following is a script where the empty variable is replaced by single quotes. If the variable is not empty then we have the correct substitution.

$ set -x;  aa=""; bb=`curl "$aa" -vvv`; set +x
+ aa=
++ curl '' -vvv

The thing to notice is the single quotes in place of the empty variable.

When variable is not empty, everything works fine as in:

$ set -x;  aa="google.com"; bb=`curl "$aa" -vvv`; set +x
+ aa=google.com
++ curl google.com -vvv

Q1: Why is an empty variable or a variable with space resulting in single quotes being introduced? Q2: How do I prevent the single quotes in lieu of the empty variable?

Now, I can remove the double quotes and everything works fine but I need to preserve spaces if there are any.

Thanks.

Khanna111
  • 3,627
  • 1
  • 23
  • 25

3 Answers3

6

Single quotes are not being introduced, they are just being used to show you that you are passing an empty argument. The double quotes you use are causing the empty argument to be passed. If you want no argument but want to allow whitespace in the variable, you'll have to do something like:

curl ${aa:+"$aa"} -vvv

This is different than curl ${aa+"$aa"} -vvv when aa is the empty string, but from your description it appears you want the former.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Thanks. Why would curl interpret an empty argument or space with an actual argument? Should it not ignore it? Is this a curl issue or shell issue? – Khanna111 Aug 31 '17 at 18:56
  • 1
    If you pass the empty string as an argument, then that is the argument that is passed. Why should curl ignore it? It's neither a shell issue nor a curl issue; it's a usage error. You are passing curl an empty argument, and curl (IMO correctly) doesn't treat that argument in a special manner, but tries to use the empty string as a url. – William Pursell Aug 31 '17 at 20:32
1

You are seeing the single quotes because you used double quotes around $aa, so curl sees the empty string as your parameter. You won't get this effect if you drop the double quotes like this:

 set -x;  aa=""; bb=`curl $aa -vvv`; set +x
Kamran
  • 843
  • 1
  • 8
  • 19
  • 3
    Note that leaving the double-quotes off also means the variable's value will be subject to word splitting and wildcard expansion, which can cause unexpected behavior. – Gordon Davisson Aug 30 '17 at 02:32
0

This is because you enclosed variable substitution into double quotes. $aa expands to empty string, which is placed into quotes, therefore producing quotes with nothing. In this case curl will see 3 arguments in that order: curl, <empty string>, -vvv.

If you remove double quotes round $aa, the second argument will not be passed to curl, and it will see only curl and -vvv in argv parameter in it's main function:

$ set -x;  aa=""; bb=`curl $aa -vvv`; set +x
+ aa=
++ curl -vvv
Oleg Andriyanov
  • 5,069
  • 1
  • 22
  • 36