[英]Test if file exists with a function in shell script
I have the following script, basically a function and an IF我有以下脚本,基本上是一个函数和一个 IF
file_exists() {
if [ -f "$1" ]; then
return 0
else
return 1
fi
}
if [[ $(file_exists "LICENSE") ]]; then
echo "YES"
else
echo "NO"
fi
But this code always returns NO.但是这段代码总是返回 NO。 I know the IF statement expects to get a 0 to be true, but I don't understand why it doesn't work
我知道 IF 语句期望得到 0 为真,但我不明白为什么它不起作用
When using the return value of a function in an if-statement, you do not need to wrap it in [[]]
.在 if 语句中使用函数的返回值时,不需要将其包装在
[[]]
。 You can replace你可以更换
if [[ $(file_exists "LICENSE") ]]; then
with和
if file_exists "LICENSE"; then
As for the convention of 0=true
and 1=false
, it's not preferred to write them out explicitly in return statements .至于
0=true
和1=false
的约定,最好不要在 return 语句中明确写出它们。 The body of your file_exists
function can be reduced to file_exists
函数的主体可以简化为
file_exists() {
[ -f "$1" ]
}
IMHO if..else redundant here.恕我直言,如果..else 在这里多余。 Use your function like this:
像这样使用你的函数:
file_exists $FILENAME && echo ok || echo notok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.