【问题标题】:Assign query result to variable and access it from other file将查询结果分配给变量并从其他文件访问它
【发布时间】:2016-03-09 13:13:17
【问题描述】:

我有两个文件,分别是 file1.shfile2.sh

file1.sh 包含 DB2 查询,该查询返回员工表中的员工总数。

现在我想将员工总数分配到文件file1.sh 中的一个变量中。

文件 1

#!/bin/bash
#database connection goes here
echo The total number employees: 
db2 -x "select count(*) from employee"

当我在上面运行显示员工总数的文件时。

但是

我想将该总数存储到某个变量中,并希望它可以从另一个文件file2.sh 访问。

文件 2

#!/bin/bash
#Here i want to use total number of employees 
#Variable to be accessed here

【问题讨论】:

    标签: bash shell db2


    【解决方案1】:

    使用以下两个脚本,driver.shchild.sh

    driver.sh

    #!/bin/bash
    
    cnt=`./child.sh syscat.tables`
    echo "Number of tables:  ${RESULT}"
    cnt=`./child.sh syscat.columns`
    echo "Number of columns:  ${RESULT}"
    

    child.sh

    #!/bin/bash
    db2 connect to pocdb > /dev/null 2>&1
    
    cnt=`db2 -x "select count(*) from ${1}"`
    
    db2 connect reset > /dev/null 2>&1
    db2 terminate > /dev/null 2>&1
    
    echo ${cnt}
    

    结果

    [db2inst1@dbms stack]$ ./driver.sh 
    Number of tables:  474
    Number of columns:  7006
    
    [db2inst1@dbms stack]$ ./child.sh syscat.columns
    7006
    

    【讨论】:

    • 有在线终端可以查到吗?
    • 您可以从命令行运行 driver.sh。您也可以从命令行运行 ./child.sh,传入参数,如 syscat.columns。我在答案中添加了一个运行 child.sh 的示例。
    • 我可以在 driver.sh 文件中使用cnt 吗?
    • child.sh 中的变量 cnt 可以在变量 RESULT 中访问,或者您想在 driver.sh 中调用 RESULT 的任何其他内容。
    • 那么你能根据这个编辑你的答案吗?我的意思是在 driver.sh 文件中使用 cnt 来显示该文件的记录数。
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多