我有以下脚本,基本上是一个函数和一个IF
file_exists() {
if [ -f "$1" ]; then
return 0
else
return 1
fi
}
if [[ $(file_exists "LICENSE") ]]; then
echo "YES"
else
echo "NO"
fi
但是此代码始终返回NO。我知道IF语句期望得到一个0,但我不明白为什么它不起作用
在if语句中使用函数的返回值时,不需要将其包装在[[]]
中。您可以替换
if [[ $(file_exists "LICENSE") ]]; then
with
if file_exists "LICENSE"; then
关于0=true
和1=false
的约定,它是not preferred to write them out explicitly in return statements。 file_exists
函数的主体可以简化为
file_exists() {
[ -f "$1" ]
}