Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file into variable while suppressing "No such file or directory" error

Tags:

bash

I want to read text file contents into a Bash variable, suppressing the error message if that file does not exist. In POSIX, I would do

var=$(cat file 2>/dev/null)

But I read (e.g. at How to read a file into a variable in shell) that it's a Useless Use of Cat in Bash. So, I'm trying those:

var=$(< file 2>/dev/null)
var=$(< file) 2>/dev/null

But it the first doesn't read an existing file, and both print -bash: file: No such file or directory if the file does not exist. Why doesn't this work? (Especially: What completely breaks the first one?)

What does work is this:

{ var=$(< file); } 2>/dev/null

But it's ugly and cumbersome. So, is there a nicer syntax, or is this a valid use of cat after all?

like image 233
Ingo Karkat Avatar asked Aug 08 '17 12:08

Ingo Karkat


2 Answers

With BASH it is easy to test if file exists before reading it in

[ -e file ] && var=$(< file )

As Inian points in the comments the file might exist but the user might not have sufficient rights for reading it. The -r test would take care of that.

[ -r file ] && var=$(< file )
like image 162
Dmitri Chubarov Avatar answered Oct 23 '22 18:10

Dmitri Chubarov


var=$(cat file 2>/dev/null)

This is a Useful Use of Cat. It enforces an order of operations: stderr is redirected before file is opened. It serves a purpose. Don't feel bad about using it.

like image 24
John Kugelman Avatar answered Oct 23 '22 19:10

John Kugelman