5

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?

0

2 Answers 2

6

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="
Sign up to request clarification or add additional context in comments.

5 Comments

A bit less efficient but shorter to write x=$(cat file 2>&-).
Is X unset or empty in the failure case here?
@CharlesNicholson Empty.
Cool, thanks! (will "accept" after the 5-minute cool-off expires). I notice you put a space after the < inside the $(<foo.txt) expression. Is that stylistic or functional?
@CharlesNicholson Purely stylistic. I like having blanks around my redirections, and the manual also has a blank there ;)
3

You may want to use this one lines using success/error after file existence check:

[[ -f foo.txt ]] && s=$(<foo.txt) || s=''

s=$(<foo.txt) will be executed if file exists otherwise s='' gets executed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.