Reputation: 353
I have a problem to print out the result when a file does not exist. Let's say I use this code in bash
v1=`cat /ieee80211/phy2/rcstats`
echo $v1
When the file exists, it will display the value like this
0.8
0.6
0.3
But when file doesn't exist, it will just display :
cat: /ieee80211/phy2/rcstats: No such file or directory
How to change that warning into 1.0
?
What I know, I just do like this
if [! -f $v1]; then
echo "1.0"
fi
but the result it will just print 1.0
when the file exists, and the warning still appears
What should I do? Thank you
Upvotes: 0
Views: 201
Reputation: 26259
The best error handling in this case is to check whether the file exist and if so, do the cat
, not the other way round.
Like this:
file="/ieee80211/phy2/rcstats"
if [ -f $file ]
then
v1=$(< $file)
fi
Upvotes: 1
Reputation: 46823
If you don't want to handle the case where the file doesn't exist, you might as well just use:
{ v1=$( </ieee80211/phy2/rcstats ) ; } 2>/dev/null
echo "$v1"
Note. Avoid using backticks, use $(...)
instead.
Upvotes: 0
Reputation: 798626
[
is a command. It needs spaces between it and its first argument.
if [ ! ... ]; then
^
here
Upvotes: 4