-3

In the following script I am testing how to count how many times a command runs.

#!/bin/bash

echo "Hello"
scount=$?
if [ $scount -eq 0 ]; then
    
    count=$(cat ${scount})
else
    count=0
fi
((count++))

echo ${count} > ${scount}
echo "Scount: $count"

This is the output I receive. I am confused as to why I am getting the cat: 0: No such file or directory message.

Hello
cat: 0: No such file or directory
Scount: 1
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • `I am confused as to why I am getting the cat: 0: No such file or directory message.` Because you're calling `cat ${scount}` with `scount` = `0`. – tkausl Jan 10 '21 at 13:21
  • 1
    It's not creating a file, which is why there's no such file. What did you expect from `cat` given that you've just verified that scount is zero? – jonrsharpe Jan 10 '21 at 13:21
  • 1
    What are you actually trying to do here? Are you aware of what `$?` means? And that a file needs to already exist if you supply it as an argument to `cat` – costaparas Jan 10 '21 at 13:22

2 Answers2

0

As said on Unix manual for cat

cat - concatenate files and print on the standard output

And as said on $? here

$? is the exit status of the last executed command.

So:

  • cat command wants a file to read and print in standard output
  • $? is a number and its value is 0, cause the last command executed in that point of the script was echo "Hello" (well executed = status 0)

You're trying to do something like cat 0 so with this:

count=$(cat ${scount})
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
0
        echo "Hello"
        scount=$?
        if [ $scount -eq 0 ]; then
            
            count=$(cat ${scount})
        else
            count=0
        fi

I think you were wanting to assign 0 to count and used cat instead of echo

count=$(echo "$scount")

But that's a useless use of echo

count=$scount

But now you're assigning 0 to count in both branches of the if statement, so you can remove the whole if:

        echo "Hello"
        scount=$?
        count=0
glenn jackman
  • 238,783
  • 38
  • 220
  • 352