簡體   English   中英

在同一腳本中重用包含變量的代碼 bash

[英]Reuse code that contains variables in same script bash

我在bash中有一小段代碼,如下所示

#!/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"

預計 output 低於

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

但我什么也沒得到,因為 output

我知道我在分配變量之前引用了它。

這里的想法是使用可重用的代碼,而不是在許多地方編寫相同的代碼

我怎樣才能達到我想要的

你應該得到

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

正如你已經提到的原因是

我知道我在分配變量之前引用了它。

實現這一點的一種方法

$ 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

更新

根據評論

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

這與發布的問題不同,最好定義一個 function

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

$ getquery $RANDOM

select * from table where id = 12907

您可以創建一個 function 並通過為其分配變量在不同的地方調用 function

#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM