我对使用单括号或双括号感到困惑。看看这段代码:
dir="/home/mazimi/VirtualBox VMs"
if [[ -d ${dir} ]]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
尽管字符串包含空格,但它工作得很好。但是当我将其更改为单括号时:
dir="/home/mazimi/VirtualBox VMs"
if [ -d ${dir} ]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
它说:
./script.sh: line 5: [: /home/mazimi/VirtualBox: binary operator expected
Run Code Online (Sandbox Code Playgroud)
当我将其更改为:
dir="/home/mazimi/VirtualBox VMs"
if [ -d "${dir}" ]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
它工作正常。有人可以解释发生了什么吗?什么时候应该在变量周围分配双引号,"${var}"
以防止空格引起的问题?
这两者有什么区别吗。
[[ $a == z* ]]
Run Code Online (Sandbox Code Playgroud)
和
[ $a == z* ]
Run Code Online (Sandbox Code Playgroud)
我可以举一个例子,他们会有不同的输出吗?
此外, 的工作方式[[ ]]
与[ ]
?
我正在检查我的主题的更新脚本
我有 2 个文本文件。第一个称为“current.txt”并包含当前版本。4.1.1
该文本文件中有字符串。
第二个称为“latest.txt”并包含最新版本。4.2
此文本文件中有字符串。
所以这是代码
echo "Checking update";
x=$(cat ./current.txt)
y=$(cat ./latest.txt)
if [ "$x" -eq "$y" ]
then
echo There is version $y update
else
echo Version $x is the latest version
fi
Run Code Online (Sandbox Code Playgroud)
这意味着如果 current.txt 与 latest.txt 不同,那么它会说“有 4.2 版更新”。如果不是,它会说“版本 4.1.1 是最新版本”
但是当我尝试运行它时。我收到这个错误
Checking update
./test.sh: line 4: [: 4.1.1: integer expression expected
Version 4.1.1 is the latest version
Run Code Online (Sandbox Code Playgroud)
那么我做错了什么?
来自 bash 手册,用于条件表达式
Run Code Online (Sandbox Code Playgroud)string1 == string2 string1 = string2
如果字符串相等,则为真。
当与该
[[
命令一起使用时,它会执行上述模式匹配(参见第 3.2.4.2 节 [条件构造],第 10 页)。
“模式匹配”在这里是什么意思?
什么是“模式匹配”?
如果不[[
与其他命令一起使用,但与其他命令一起使用,“this”执行什么?
'=' 应该与
test
posix 一致性命令一起使用。
POSIX 在这里说什么?
反对的句子是什么?
可以==
和test
命令一起使用吗?我试过了,似乎是的。
可以=
用除此之外其它命令中使用test
?我试着=
用[[
和[
,似乎是肯定的。
==
和之间有什么区别=
?
在bash 4.3,我试图==
和=
同test
,[[
和[
。==
并且=
看起来是一样的我。
可以==
和=
在任何条件表达式互换使用?
谢谢。
我尝试使用这个:
$ if [$a == 1] then { echo 'yes'; } fi;
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误:
-bash: syntax error near unexpected token `}'
Run Code Online (Sandbox Code Playgroud)
什么是正确的格式?我尝试了几个都没有运气。
使用此运算符时,我的脚本出现错误。我有一些在线文档,双等号应该可以工作。有任何想法吗?
Zsh 参考指南:http: //zsh.sourceforge.net/Doc/Release/Conditional-Expressions.html
脚本:
#!/bin/zsh
if [ $_user == "root" ]; then
echo "root"
else
echo "not root"
fi
Run Code Online (Sandbox Code Playgroud)
运行它:
$ ./script.sh
./script.sh:3: = not found
Run Code Online (Sandbox Code Playgroud)