[英]Execute gcloud commands in a bash script
在執行bash腳本期間, gcloud init
命令不提供登錄提示。
但是在腳本結束后我手動鍵入了exit
命令后,它提供了登錄名。
vagrant@vagrant-ubuntu-trusty-64:~$ exit
logout
Welcome! This command will take you through the configuration of gcloud.
Settings from your current configuration [default] are:
Your active configuration is: [default]
Pick configuration to use:
[1] Re-initialize this configuration [default] with new settings
[2] Create a new configuration
Please enter your numeric choice: 1
Your current configuration has been set to: [default]
To continue, you must log in. Would you like to log in (Y/n)?
我的bash腳本:
#!/usr/bin/env bash
OS=`cat /proc/version`
function setupGCE() {
curl https://sdk.cloud.google.com | bash
`exec -l $SHELL`
`gcloud init --console-only`
`chown -R $USER:$USER ~/`
}
if [[ $OS == *"Ubuntu"* || $OS == *"Debian"* ]]
then
sudo apt-get -y install build-essential python-pip python-dev curl
sudo pip install apache-libcloud
setupGCE
fi
在bash腳本執行過程中如何獲得登錄提示?
發布的代碼段存在許多問題。
正確的代碼段是(可能):
function setupGCE() {
curl https://sdk.cloud.google.com | bash
gcloud init --console-only
chown -R $USER:$USER ~/
}
您發現自己的原始文件的第一個錯誤(至少是它的原因而不是原因)是exec -l $SHELL
阻止進度。 這樣做是因為您已經運行了一個交互式外殼程序,該外殼程序正在等待您的輸入,並且該函數正在等待該進程退出后再繼續。
此外, exec
用生成的進程替換當前進程。 你在這里真幸運。 如果沒有將對exec
的調用包裝在單引號中,則當您退出啟動的$SHELL
時,您的函數將完全退出shell腳本。 但是, exec
只是替換了反引號添加的子外殼,因此您剩下一個子進程,該子進程可以安全地退出並將您返回到父/主腳本。
第二個問題是反引號會運行它們所包圍的命令,然后將其替換為輸出。 這就是為什么
echo "bar `echo foo` baz"
輸出bar foo baz
等。(在運行該命令之前運行set -x
,以查看實際上正在運行的命令。)因此,當您編寫時
`gcloud init --console-only`
您的意思是“運行gcloud init --console-only
然后獲取其輸出並用該命令替換命令”,然后它將嘗試將輸出作為命令本身運行(這可能不是您想要的)。 在其他行上類似。
盡管chown
和gcloud init
可能不會返回任何內容,所以這里碰巧沒有問題,因此生成的命令行為空。
高管exec -l $SHELL
搞砸了所有的麻煩。 我將其更改為source ~/.bashrc
,現在可以使用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.