我試圖通過在 bash env 中宣告 $username 和 $password 變數并將它們作為輸入傳遞給腳本,使這個互動式腳本以非互動式方式接受輸入。通過運行 ./input.sh <<< "$username"
#!bin/bash
read username
read password
echo "The Current User Name is $username"
echo " The Password is $password"
有沒有辦法將兩個變數都作為輸入傳遞?因為根據我的嘗試,這種方式只需要一個輸入。
uj5u.com熱心網友回復:
所以,盡可能地接近你最初的嘗試(但我懷疑這是解決任何實際問題的最佳解決方案),你要問的是“我如何通過這里的字串傳遞 2 行”。
一個可能的答案是
./input.sh <<< "$username"$'\n'"$password"
here-strings是您在使用<<<. 當你輸入./input.sh <<< astring它時,有點像你在輸入echo astring | ./input.sh: 它使用字串作為標準輸入./input.sh。由于您read的 s 讀取行,您需要 2 行作為標準輸入來實作您想要的。你可以這樣做:(echo "$username" ; echo "$password") | ./input.sh. 或者無論如何都會產生 2 行,其中$username一行帶有$password并將這 2 行重定向為標準輸入./input.sh
但是使用here-string,您不能只分成幾行......除非您在輸入字串中明確引入回車符(\n用c表示法)。我在這里使用$'...'允許 c 轉義的符號來執行此操作。
編輯。為了好玩,我在這里包括了我在評論中寫的其他解決方案,因為你不是特別需要這里的字串。
(echo "$username" ; echo "$password") | ./input.sh
{echo "$username" ; echo "$password" ; } | ./input.sh
printf "%s\n" "$username" "$password" | ./input.sh
./input.sh < <(echo "$username" "$password")
./input.sh < <(printf "%s\n" "$username" "$password")
加上當然改變的解決方案./input.sh
#!bin/bash
username="$1"
password="$2"
echo "The Current User Name is $username"
echo " The Password is $password"
用./input "$username" "$password"
或者
#!bin/bash
echo "The Current User Name is $username"
echo " The Password is $password"
用username="$username" password="$password" ./input.sh
uj5u.com熱心網友回復:
最簡單的方法是這樣的:
#!/bin/bash
echo "The Current User Name is $1"
echo "The Password is $2"
$1 代表第一個給定引數,$2 代表第二個。
[user@vm ~]$ input.sh "user" "password"
在引號 ("") 內放置您要傳遞的引數。
如需更專業/更強大的解決方案,請查看:Redhat: Bash Script Options/Arguments
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512845.html
標籤:linux重击壳环境变量
