Shell和JavaScript相互調(diào)用,以及相互傳參

一、shell腳本調(diào)用js腳本,以及傳參

1、js代碼
// 打印所有參數(shù)
console.log('打印所有參數(shù):');
process.argv.forEach((index, value) => console.log(index, value));
// 獲取傳遞的參數(shù)
var cp1 = process.argv[2];
var cp2 = process.argv[3];
console.log('打印傳遞的參數(shù): ' + cp1 + ' ' + cp2);
2、shell代碼
appid="id123"
appname="小程序"
# 執(zhí)行js并傳參數(shù)
node miniprogram.js $appid $appname
3、調(diào)用shell腳本,將shell中參數(shù)傳遞給js
sh test.sh
4、打印傳遞的參數(shù)
└─[0] <git:(master?) > sh test.sh 
這是 miniprogram.js
打印所有參數(shù):
/usr/local/bin/node 0
/Users/wxq/Desktop/testjs/miniprogram.js 1
id123 2
小程序 3
打印傳遞的參數(shù): id123 小程序
在這里可以看到所需的參數(shù)值位于索引2和3上。
shell調(diào)用js

二、js腳本調(diào)用shell腳本,以及傳參

1、js代碼
// Nodejs下引入模塊child_process實(shí)現(xiàn)調(diào)用shell
var child = require('child_process');

let appid = 'id123'
let appname = "小程序"
let command = 'bash ./test.sh ' + appid + ' ' + appname
// 調(diào)用shell腳本并傳參數(shù)
child.exec(command, function(err, sto) {
    // sto才是真正的輸出
    console.log('sto: ' + sto);
})
2、shell代碼
echo "從js中獲取的參數(shù)為:$1 $2"
3、調(diào)用js腳本,將js中參數(shù)傳遞給shell
node miniprogram.js 
4、打印傳遞的參數(shù)
└─[0] <git:(master?) > node miniprogram.js 
sto: 從js中獲取的參數(shù)為:id123 小程序
js調(diào)用shell

三、js腳本中調(diào)用終端命令

let command1 = 'ls'
let command2 = '/usr/local/bin'
let command3 = 'git pull'
let command4 = 'npm list'
let command5 = 'node -v'

import shell from 'shelljs'

shell.exec('pwd')
shell.exec(command1)
shell.exec('open ' + command2)
shell.exec(`open "${command2}"`)
shell.exec(command3)
shell.exec(command4)
shell.exec(command5)

Demo地址:js-shell-intercall

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容