linux - 使用shell脚本中的函数测试文件是否存在
问题描述
我有以下脚本,基本上是一个函数和一个 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
和
if file_exists "LICENSE"; then
至于 and 的约定0=true
,1=false
最好不要在 return 语句中明确地写出来。你的file_exists
函数体可以简化为
file_exists() {
[ -f "$1" ]
}
推荐阅读
- sql - 如何设置输入控件?
- pip - 我可以只使用 pip 使直接安装的软件包保持最新吗?
- sql - 如何计算 postgresql 中的空值?
- sql-server - SSMS/SSRS - 从查询中获取 SSRS 数据集使用的存储过程名称
- node.js - MongoDB $addFields 和 $in 合计
- azure - Azure DevOps 如何将自定义内部版本号格式获取到 YAML 构建管道?
- java - Java/Android:验证十进制编辑文本的可接受值的范围
- python - 在 Python 中将元组元素切片和堆叠成矩阵
- shell - 使用嵌入空格加密文件
- python - 为什么我在安装 python-weka-wrapper3 时出错,尽管安装了 Visual C++ 14.0