Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this shell variable not set correctly

Tags:

linux

bash

I have a specific user on my linux machine with whom the following command

json='[{"date":"2016"}]' && echo ${json}

outputs 1 and not [{"date":"2016"}].

With all other users on my machine this works correctly. When I change the command to (omitting the 1)

json='[{"date":"206"}]' && echo ${json}

it works correct, too.

I am desperately seeking the config difference of this user that leads to this effect. But to be honest, I have no idea.

Any hints out there?

like image 826
heinob Avatar asked Jan 26 '16 14:01

heinob


1 Answers

Square brackets create a glob expression matching any single character within them.

[123] matches a file named 1, 2, or 3; similarly, [{"date":"2016"}] matches files named d, a, t, e, :, 2, 0, 1, 6, ", { or }.

You aren't noticing it for users who don't have any file thusly named because the default behavior of a glob expression with no matches is no evaluate to itself (though this default can be modified with shopt -s nullglob, in which case a glob with no matches evaluates to nothing).

Quote your expansion -- echo "$json" -- to avoid this.


To reproduce:

json='[{"date":"2016"}]'
owd=$PWD
tempdir=$(mktemp -d "${TMPDIR:-/tmp}/test.XXXXXX")
cd "$tempdir" && {
  touch 1
  echo "With the bug: "    $json
  echo "Without the bug: " "$json"
}

# cleanup
cd "$owd"
rm -rf "$tempdir"
like image 126
Charles Duffy Avatar answered Nov 12 '22 16:11

Charles Duffy