Ubuntu 16.04 - 尝试微调
这是我的代码
#!/bin/bash
# if the .md5sum file doesn't exists
# or if the .md5sum file exists && doesn't match, recreate it
# but if the .md5sum file exists && matches then break and log
csvfile=inventory.csv
if [ ! -f .md5sum ] || [ -f .md5sum ] && [ ! md5sum -c .md5sum >/dev/null ]; then
md5sum "$csvfile" > .md5sum
else
echo "$csvfile file matched md5sum ..."
break
fi
我在构建会产生新的 .md5sum 的条件语句时遇到问题。我试图找出条件语句的哪一部分是错误的,这就是 shellcheck 告诉我的。
root@me ~ # shellcheck run.sh
In run.sh line 8:
if [ ! -f .md5sum ] || [ -f .md5sum ] && [ ! md5sum -c .md5sum >/dev/null ]; then
^-- SC1009: The mentioned parser error was in this if expression.
^-- SC1073: Couldn't parse this test expression.
^-- SC1072: Expected "]". Fix any mentioned problems and try again.
我可以通过一些比较来完成整个过程,但我想如果我加入比较,我将获得更快、更干净的脚本。
我还检查了 Jesse_P 的代码
#!/bin/bash
csvfile=inventory.csv
echo "hello" > inventory.csv
md5sum "$csvfile" > .md5sum
echo "well hello" > inventory.cvs
if [[ ! -f .md5sum ]] || [[ -f .md5sum && ! md5sum -c .md5sum >/dev/null ]]; then
echo "All conditiions have been met to generate a new md5sum for inventory.csv ..."
md5sum inventory.csv > .mds5sum
fi
exit 0
然后我使用了shellcheck
root@0003 ~ # shellcheck run.sh
In run.sh line 8:
if [[ ! -f .md5sum ]] || [[ -f .md5sum && ! md5sum -c .md5sum >/dev/null ]]; then
^-- SC1009: The mentioned parser error was in this if expression.
^-- SC1073: Couldn't parse this test expression.
^-- SC1072: Expected "]". Fix any mentioned problems and try again.
答案1
正确的代码
#!/bin/sh
if [ ! -f .md5sum ] || [ -f .md5sum ] && ! md5sum -c .md5sum > /dev/null
then
echo "All conditions have been met to generate a new md5sum for inventory.csv ..."
md5sum inventory.csv > .mds5sum
fi
解析
[ ! -f .md5sum ]
[ -f .md5sum ]
这些是普通test
命令,因此 POSIX-ly[...]
不需要双括号。
! md5sum -c .md5sum > /dev/null
这不是一个test
命令,所以它周围没有括号。