Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reading words from variable in shell script? #179

Closed
ghost opened this issue May 19, 2022 · 1 comment
Closed

Reading words from variable in shell script? #179

ghost opened this issue May 19, 2022 · 1 comment

Comments

@ghost
Copy link

ghost commented May 19, 2022

I'm trying to use jo in a shell script by appending key value-pairs to a variable, and passing this as an argument to jo, but I'm not getting the expected output:

jo_script.sh:

#!/bin/bash

value0="foo"
value1="bar"
value2="foo bar"

string="'key0=${value0}' 'key1=${value1}' 'key2=${value2}'"

# Contents of string: 'key0=foo' 'key1=bar' 'key2=foo bar'

jo "$string"

Output:

{"'key0":"foo' 'key1=bar' 'key2=foo bar'"}

Expected output:

{"key0":"foo","key1":"bar","key2":"foo bar"}

Any ideas why this is happening?

@gromgit
Copy link
Collaborator

gromgit commented May 20, 2022

In short, jo "$string" stopped word-splitting from happening, because you quoted $string. Removing the double quotes doesn't work either, because your key2 value has a internal space which would also be split.

What you're trying to do (build a list of arguments for a command) is such a common task that there's a bash idiom for it: Use arrays. Specifically:

$ value0="foo"
$ value1="bar"
$ value2="foo bar"

$ arr=("key0=${value0}" "key1=${value1}" "key2=${value2}")

$ jo "${arr[@]}"
{"key0":"foo","key1":"bar","key2":"foo bar"}

@gromgit gromgit closed this as completed May 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant