0

I have a small block of code in bash like below

#!/bin/bash

query="select * from table where id = ${row_id}"

row_id=1
echo "$query"


row_id=3
echo "$query"


row_id=4
echo "$query"

expected output is below

select * from table where id = 1
select * from table where id = 3
select * from table where id = 5

But I am getting nothing as output

I know I am referencing variable before assigning it.

The idea here is to use reusable code instead of writing the same code at many places

How can I achieve what I want

2
  • 1
    Use a function. Commented Mar 5, 2021 at 21:56
  • 1
    You're getting no output? It seems that select * from table where id = is not "nothing as output". Commented Mar 5, 2021 at 22:27

2 Answers 2

1

You can create a function and call the function at various place by assign variable to it

#!/bin/bash

# create a function with variable and write your command
# here your command is print the query 
my_function_name(){
arg1=$1
echo "select * from table where id = ${arg1}"
}

# assign varaible 
row_id=1

# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")

echo $query


# assign varaible 
row_id=2

# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")

echo $query

# assign varaible 
row_id=3

# print the ourput of function when above variable is assigned
query=$(my_function_name "$row_id")

echo $query
Sign up to request clarification or add additional context in comments.

Comments

1

you should be getting

select * from table where id =
select * from table where id =
select * from table where id =

and as you already mentioned the reason is

I know I am referencing variable before assigning it.

One way to implement this

$ for row_id in 1 3 5; 
  do 
    echo "select * from table where id = $row_id"; 
  done

select * from table where id = 1
select * from table where id = 3
select * from table where id = 5

UPDATE

Based on the comment

Here if row_id is a random variable I get as part of another query then
how do I get the correct query as my output

which is different from the posted question, better to define a function

$ getquery() { echo "select * from table where id = $1"; }

$ getquery $RANDOM

select * from table where id = 12907

1 Comment

Thank you for you answer. Here if row_id is a random variable I get as part of another query then how do I get the correct query as my output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.