簡體   English   中英

Bash Restrict父腳本命令行參數結轉到子腳本參數

[英]Bash Restrict parent script command line arguments carry forward to child scripts arguments

我們有父bash腳本

parent_source.bash

#!/bin/bash

source child_test.bash

在child_test.bash內部

echo $@ 
#Doing some validation checks for $@, for child_script command line arguments are optional

當執行時

 source parent_source.bash one two

子腳本在$ @中使用“一個”和“兩個”,因此驗證失敗,不將其視為給子腳本的零參數。 假設子腳本有2個命令行參數。

但是,如果我們也為子代提供命令行參數,那也可以正常工作。

有人可以幫我們嗎

謝謝

在執行source命令時,實際上是將child_test.bash的內容注入到parent_source.bash腳本中,然后在執行child_test.bash的第一行時將其child_test.bash ,即:

echo $@

它實際上是指傳遞給父腳本的參數,因為命令的范圍實際上在parent_source.bash腳本上。

我建議在執行腳本時不要將內容注入父腳本。

像這樣:

parent_source.bash

#!/bin/bash

./child_test.bash

child_test.bash

echo $@ 
#Doing some validation checks for $@, for child_script command line arguments are optional

您缺少$@選項來將parent_source.bash的值傳遞給child_test.bash

parent_source.bash

#!/bin/bash

source child_test.bash $@

在child_test.bash內部

echo $@ 

當執行時

 source parent_source.bash one two

由於從父級獲取子腳本的source ,父腳本的shell環境也將傳播到子腳本的內容。 因此,提供給父腳本的參數可用,並且可以在子腳本上使用$@進行擴展。

您可以將參數保存到數組中的父腳本中,然后在獲取子腳本之前取消設置位置參數,以防止將其提供給子腳本。 因此,您的父腳本可以采用以下形式:

args=( $@ )
set --
source child_test.sh

暫無
暫無

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

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