簡體   English   中英

通過bash腳本將參數傳遞到/ bin / bash

[英]Passing arguments to /bin/bash via a bash script

我正在編寫一個bash腳本,該腳本需要多個命令行參數(可能包括空格),並將所有這些參數通過登錄shell傳遞給程序(/ bin / some_program)。 從bash腳本調用的登錄shell將取決於用戶的登錄shell。 假設在此示例中,用戶使用/ bin / bash作為他們的登錄shell ...但是它可能是/ bin / tcsh或其他任何東西。

如果我知道將有多少個參數傳遞給some_program,則可以在bash腳本中添加以下幾行:

#!/bin/bash
# ... (some lines where we determine that the user's login shell is bash) ...
/bin/bash --login -c "/bin/some_program \"$1\" \"$2\""

然后按以下方式調用上述腳本:

my_script "this is too" cool

通過上面的示例,我可以確認some_program接收到兩個參數,“ this too too”和“ cool”。

我的問題是...如果我不知道會傳遞多少個參數怎么辦? 我想將所有發送到my_script的參數傳遞給some_program。 問題是我不知道該怎么做。 以下是一些無效的內容

/bin/bash --login -c "/bin/some_program $@"     # --> 3 arguments: "this","is","too"
/bin/bash --login -c /bin/some_program "$@"     # --> passes no arguments

在bash手冊中引用-c

如果存在-c選項,則從字符串讀取命令。 如果字符串后面有參數,則將它們分配給位置參數, 從$ 0開始

為我工作:

$ cat x.sh
#!/bin/bash
/bin/bash --login -c 'echo 1:$1 2:$2 3:$3' echo "$@"
$ ./x.sh "foo bar" "baz" "argh blargh quargh"
1:foo bar 2:baz 3:argh blargh quargh

我不知道您是如何得出“不通過參數”結論的,也許您錯過了$0位?

避免將變量嵌入其他腳本中,而應將其作為參數傳遞。 在這種情況下:

bash --login -c 'some_program "$@"' some_program "$@"

-c'...'之后的第一個參數設為$ 0,因此我只在其中放入some_program。

附帶一提,需要登錄shell是一個奇怪的要求。 用戶不登錄嗎?

暫無
暫無

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

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