大佬教程收集整理的这篇文章主要介绍了linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
挑战在于它需要是可以在Windows PowerSHell和bash / sHell上运行的SAME脚本.
这是sHell脚本:
#!/bin/bash # download a script wget http://www.example.org/my.script -O my.script # set a couple of environment variables export script_source=http://www.example.org export some_value=floob # Now execute the downloaded script bash ./my.script
这与PowerSHell中的情况相同:
wget http://www.example.org/my.script -O my.script.ps1 $env:script_source="http://www.example.org" $env:some_value="floob" PowerSHell -File ./my.script.ps1
所以我想知道这两个脚本是否可以合并并在任一平台上成功运行?
我一直在试图找到一种方法将它们放在同一个脚本中,并让bash和PowerSHell.exe忽略错误,但没有成功.
任何猜测?
NB.这是有效的,因为两个sHell中的语法重叠,并且您的脚本很简单 – 运行命令并处理变量.如果您尝试使用更高级的脚本(if / then,for,switch,case等)用于任何一种语言,另一种可能会抱怨.
将其保存为dual.ps1,以便PowerSHell对它感到满意,chmod x dual.ps1因此Bash将运行它
#!/bin/bash function DoBashThings { wget http://www.example.org/my.script -O my.script # set a couple of environment variables export script_source=http://www.example.org export some_value=floob # Now execute the downloaded script bash ./my.script } "DoBashThings" # This runs the bash script,in PS it's just a String "exit" # This quits the bash version,in PS it's just a String # PowerSHell code here # -------------------- Invoke-Webrequest "http://www.example.org/my.script.ps1" -OutFile my.script.ps1 $env:script_source="http://www.example.org" $env:some_value="floob" PowerSHell -File ./my.script.ps1
然后
./dual.ps1
在任何一个系统上
编辑:您可以通过使用不同的前缀注释代码块来包含更复杂的代码,然后让每种语言过滤掉自己的代码并对其进行评估(通常的安全警告适用于eval),例如:采用这种方法(纳入Harry Johnston的建议):
#!/bin/bash #posh $num = 200 #posh if (150 -lt $num) { #posh write-host "PowerSHell here" #posh } #bash thing="xyz" #bash if [ "$thing" = "xyz" ] #bash then #bash echo "Bash here" #bash fi function RunBashstuff { eval "$(grep '^#bash' $0 | sed -e 's/^#bash //')" } "RunBashstuff" "exit" ((Get-Content $MyInvocation.MyCommand.sourcE) -match '^#posh' -replace '^#posh ') -join "`n" | Invoke-Expression
以上是大佬教程为你收集整理的linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?全部内容,希望文章能够帮你解决linux – 是否可以编写一个在bash / shell和PowerShell中运行的脚本?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。