bash - Bash one-liner for "if a file exists, read it into variable, else empty string"?
问题描述
I can write:
X=""
if [ -f foo.txt ]; then
X=$(<foo.txt)
fi
but this is 4 lines. Is there a more compact way to express this logic?
解决方案
If you do just X=$(< foo.txt)
, X
will be empty if the file doesn't exist, but you'll get an error message:
$ X=$(< foo.txt)
-bash: foo.txt: No such file or directory
If you want to suppress that (but also any other error message), you can redirect stderr to /dev/null
:
{ X=$(< too.txt); } 2> /dev/null
X
is in fact empty afterwards:
$ declare -p X
declare -- X="
推荐阅读
- c++ - 使用混合加速在第二个位图中绘制位图放大
- postgresql - 如何在视图上使用 TRIM
- oracle - 按计数选择乘法 SQL、Group By、Oracle
- php - 使用 codeigniter 和 mysql 插入数据失败
- c++ -
- python - 在 apache 上部署 django 时没有发现模块错误
- python - 获取最终预测掩码中的轮廓坐标
- qt - QFontMetrics 缺少baseline() 方法
- sql - 从 SQL Server 2008 中的数据数自动增加列
- python - 如何使用 pylucene 创建 CustomSimilarity 类?