首页 > 解决方案 > 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?

标签: bash

解决方案


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="

推荐阅读