簡體   English   中英

如何從 bash 腳本獲取 zsh 腳本?

[英]How do I source a zsh script from a bash script?

我需要從zsh腳本中提取一些變量和函數到bash腳本中。 有什么辦法嗎? 我試過的(有些是令人尷尬的錯誤,但涵蓋了一切):

. /script/path.zsh . /script/path.zsh (存在 zsh 主義,所以它失敗了)

exec zsh
. /script/path.zsh
exec bash
zsh << 'EOF'
. /script/path.zsh
EOF
chsh -s zsh
. /script/path.zsh
chsh -s bash

這個線程是我發現的最接近的線程。 不幸的是,我要導入的項目太多以至於不可行,而且這兩個腳本都不是多語言的。 但是,我需要導入的函數和變量是多語言的。

您可以根據需要“抓取”zsh 源文件,然后使用eval執行 bash 中的代碼。 下面是為一些函數執行此操作的示例:

文件script.zsh

test1() {
    echo "Hello from test1"
}

test2() {
    echo $((1 + $1))
}

文件script.sh (bash):

# Specify source script and functions
source_filename="script.zsh"
source_functions=" \
    test1          \
    test2          \
"

# Perform "sourcing"
function_definitions="$(python -B -c "
import re
with open('${source_filename}', mode='r') as file:
    content = file.read()
for func in '${source_functions}'.split():
    print(re.search(func + r'\(\).*?\n}', content, flags=re.DOTALL).group())
" )"
eval "${function_definitions}"

# Try out test functions
test1                         # Hello from test1
n=5
echo "$n + 1 is $(test2 $n)"  # 5 + 1 is 6

運行 bash 腳本,它將使用 zsh 腳本中定義的函數test1test2

bash script.sh

上面使用了 Python,特別是它的re模塊。 它只是查找funcname()形式的字符序列,並假定 function 在第一個}處結束。 所以它不是很通用,但是如果您以這種方式編寫函數,它就可以工作。

暫無
暫無

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

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