Shell 只要变量为空,就运行循环
我有一个小脚本,用于检查git配置中是否存在用户名和电子邮件,否则会提示用户输入它们:Shell 只要变量为空,就运行循环,shell,Shell,我有一个小脚本,用于检查git配置中是否存在用户名和电子邮件,否则会提示用户输入它们: GIT_USER_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'` GIT_EMAIl_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'` while [[ -z $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS ]]; do echo
GIT_USER_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
GIT_EMAIl_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
while [[ -z $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS ]]; do
echo "User name and Email are not set in git. Please enter them now..."
echo "First and Last name:"
read gitUser
git config --global user.name "$gitUser"
echo "Email:"
read gitEmail
git config --global user.email "$gitEmail"
done
但它不起作用;)
一开始,它甚至没有进入循环。
我的猜测是,与grep不同,awk确实在变量中插入了一些(隐藏的?)字符。
第二,我不确定脚本是否能识别现在有值,因为我在循环外声明了变量。我的假设错了吗
编辑:
我解决了第一个问题,用反勾号代替变量名的引号。
第二个问题仍然存在-一定有比两次声明变量更好的用法?!在壳里的时候做些什么
编辑#2:
这样做的技巧稍微好一点,但是有一个相当长的条件语句。能再短一点吗
while [[ -z $GIT_USER_EXISTS || -o $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS || -o $GIT_EMAIl_EXISTS ]]; do
echo "User name and Email are not set in git. Please enter them now..."
echo "First and Last name:"
read gitUser
git config --global user.name "$gitUser"
echo "Email:"
read gitEmail
git config --global user.email "$gitEmail"
GIT_USER_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
GIT_EMAIl_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
done
事实上,它几乎做到了这一点——它应该是“如果var已设置且为空,或者var未设置”。但是那太长了:)试着这样做:
GIT_USER_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
GIT_EMAIl_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
while [[ -z $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS ]]; do
echo "User name and Email are not set in git. Please enter them now..."
echo "First and Last name:"
read gitUser
git config --global user.name "$gitUser"
echo "Email:"
read gitEmail
git config --global user.email "$gitEmail"
GIT_USER_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
GIT_EMAIl_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
done
- 如果您测试
或$GIT\u USER\u存在
,您应该在某处声明它;)李>$GIT\u EMAIl\u存在