代码之家  ›  专栏  ›  技术社区  ›  nmr

重用在同一脚本bash中包含变量的代码

  •  0
  • nmr  · 技术社区  · 5 年前

    我有一小段代码在里面 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"
    

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

    但是我没有得到任何输出

    在分配变量之前,我知道我正在引用它。

    这里的想法是使用可重用代码,而不是在许多地方编写相同的代码

    2 回复  |  直到 5 年前
        1
  •  1
  •   User12345    5 年前

    您可以创建一个函数,并通过向其分配变量在不同的位置调用该函数

    #!/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
    
        2
  •  1
  •   karakfa    5 年前

    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
    

    这与发布的问题不同,最好定义一个函数

    $ getquery() { echo "select * from table where id = $1"; }
    
    $ getquery $RANDOM
    
    select * from table where id = 12907
    
    推荐文章