1

I am trying to convert a variable to a string format so I can use java runsql utility to insert its value into a database later. The database needs the value to be in a char format, hence string.

This is a dumbed down version of my code so I can get to the heart of what I'm asking -

#!/bin/ksh -x
value1=2018-01-01
value2=2018-02-01

mystring=$value1,$value2
echo $mystring

stringify=${'value1'},${'value2'})
echo $stringify

What happens is I get no output for stringify or depending on how I switch up the arrangement of the symbols I get the literal string 'value1' or 'value2'.

What am I doing wrong? I feel like this is very simple, maybe I've just been staring at it too long, I dunno.

4
  • Why do you have the quotes in ${'value1'}? What are they intended to do? Showing your expected output explicitly (My desired output is X, my actual output is Y) would make this question considerably easier to understand. Commented May 30, 2018 at 19:40
  • ...to be very, very clear -- every single variable you have here already is a string. mystring is a string. value1 and value2 contain strings. This code contains no non-string variables whatsoever -- so when you say "convert a variable to string format", it's not at all clear what you're asking for. Commented May 30, 2018 at 19:42
  • @WalterA OP's intended use for SQL suggests they want to quote the value. Commented May 30, 2018 at 19:46
  • Thanks @Vasan, missed that, deleted my comment. Commented May 30, 2018 at 19:49

2 Answers 2

2

You can just escape quote like this:

mystring=\'$value1\',\'$value2\'

Output:

$ echo $mystring

'2018-01-01','2018-02-01'

A simpler option to get the same output (as suggested by @CharlesDuffy) is:

mystring="'$value1','$value2'"
Sign up to request clarification or add additional context in comments.

1 Comment

I'd suggest mystring="'$value1','$value2'" instead -- easier to read without all the backslashes.
2

You can just do like this, more simpler:

#!/bin/ksh -x
value1=2018-01-01
value2=2018-02-01

mystring=$value1,$value2
echo $mystring

stringify="'$value1','$value2'" #use double-quotes around the variables
echo $stringify

Output:

2018-01-01,2018-02-01
'2018-01-01','2018-02-01'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.