簡體   English   中英

如何獲取 bash 腳本中的 JavaScript 變量值?

[英]How to get the JavaScript variable value in the bash script?

我有一個 Javascript 文件,其中包含以下代碼片段:

var test = "printValueInBashScript"

我有一個帶有以下代碼段的 bash 腳本:

#!/bin/bash
node app.js
echo "test :: ${test}" #I know this is wrong

我希望在 bash 腳本中獲取來自 js 文件 app.js 的測試值。 如您所見,我正在使用 bash 中的節點運行 app.js。 如何將 JS 的測試變量值存儲在 bash 腳本中,以便我可以將其用於進一步處理?

您可以打印該值,然后在 bash 中捕獲 output:

// test.js
const test1 = "printValueInBashScript";
console.log(test1);

// test.sh
test="$(node test.js)"
echo "test :: ${test}"

如果您需要設置多個變量,您可以讓應用程序打印 bash function 聲明,然后執行。 這種方法很方便,但不太安全(顯然,您必須信任您正在執行的代碼不會打印任何惡意內容)。 例如,它由ssh-agent使用。 這是它的樣子:

// test.js
const test1 = "printValueInBashScript";
const test1 = "printAnotherValueInBashScript";
console.log(`test1="${test1}"`);
console.log(`test2="${test2}"`);

// test.sh
eval $(node test.js)
echo "test1 :: ${test1}"
echo "test2 :: ${test2}"

暫無
暫無

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

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