这似乎是一个基本的事情,但我无法让它正常工作。我有一个 bash 脚本,我想在其中比较操作系统版本(Debian 中为 11 或 12)并根据版本执行某些操作。这是我所拥有的:
if [ cat /etc/*release | sed -n '3p' | cut -c 13-14 == '12' ]
then
perform actions
上面的命令在 Debian 11 上的命令行上运行(没有比较)并打印出 11 或 12。但是,在 Debian 12 上运行它说它是 Debian 11。有谁知道我做错了什么?
有人知道我做错了什么吗?
对于初学者来说,UUoC。为什么
cat file|sed
?只是sed -n '3p' /etc/*release
。我也会跳过无关的cut
。在我的 Centos 上:sed -n '/^VERSION=/{s/[^0-9]//g;p}' /etc/*release
给我 7
。同样,如果您使用 bash
,出于多种原因,您几乎应该始终使用 [[...]]
而不是 [...]
。
这里真正的问题是,你需要一个
$(...)
子 shell,或者至少是反引号。
$: if [ cat /etc/*release | sed -n '3p' | cut -c 13-14 == '12' ] ; then echo ok; else echo no; fi
-bash: [: missing `]'
cut: ==: No such file or directory
cut: 12: No such file or directory
cut: ]: No such file or directory
no
$: if [[ `cat /etc/*release | sed -n '3p' | cut -c 13-14` == '12' ]] ; then echo ok; else echo no; fi
no
$: if [[ 7 == $(sed -n '/^VERSION=/{s/[^0-9]//g;p}' /etc/*release) ]] ; then echo ok; else echo no; fi
ok
当出现问题时,请将您的代码粘贴到 ShellCheck。它通常会有所帮助。
Line 1:
if [ cat /etc/*release | sed -n '3p' | cut -c 13-14 == '12' ]
^-- SC1009 (info): The mentioned syntax error was in this if expression.
^-- SC1073 (error): Couldn't parse this test expression. Fix to allow more checks.
^-- SC1014 (warning): Use 'if cmd; then ..' to check exit code, or 'if [[ $(cmd) == .. ]]' to check output.
^-- SC1072 (error): Expected test to end here (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.
^-- SC1076 (error): Trying to do math? Use e.g. [ $((i/2+7)) -ge 18 ].