[英]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.