-1

I have a file /tmp/gish.dat which either contains a number (more than 0, and one or more digits) or nothing.

If there is a number present, I want my function to echo a # along with the number (eg #64). If there is no number present, I want my function to do nothing.

   get_issue() {
        if [ -f "/tmp/gish.dat" ]
        then
            iss=$(cat /tmp/gish.dat | grep -Eo '[0-9]+')
            if [[ iss =~ '[0-9]+' ]]
            then
              echo "#$iss"
            fi
        fi
    }

For some reason, the inner if never matches. Very new to bash.

codeforester
  • 39,467
  • 16
  • 112
  • 140
JMurphyWeb
  • 382
  • 1
  • 11
  • 3
    Think you're missing a dollar symbol on your variable. Change it to $iss - in the if condition. – Benjamin Rowell Mar 12 '17 at 13:03
  • Assuming your outer if works correctly, try printing the result of the shell call (iss) and check whether this worked correctly. EDIT: Pretty sure you are missing the dollar symbol, as benjamin already mentioned. – Julian Heinovski Mar 12 '17 at 13:06
  • Maybe I also suggest you look at the -s option to test if the file is empty or not :) – grail Mar 12 '17 at 15:17
  • Protip: [shellcheck](http://shellcheck.net) automatically detects issues like this – that other guy Mar 12 '17 at 16:36

3 Answers3

4

If you qoute a regex within [[...]] it is only a string.

Replace '[0-9]+' by [0-9]+.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
2

You can rewrite your code this way:

   get_issue() {
        if [ -f "/tmp/gish.dat" ]
        then
            iss=$(grep -Eo '[0-9]+' /tmp/gish.dat)
            if [[ $iss ]]
            then
              echo "#$iss"
            fi
        fi
    }

Since grep -Eo extracts just the matching numeric part, there is no need to match the extracted string against the regex again in if. [[ $iss ]] is true whenever $iss is not empty.

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

if you need to print something like #64, #45 etc then change your code as follows,

 if [ -f "/tmp/gish.dat" ]
    then
        iss=$(cat /tmp/gish.dat | grep -Eo '[0-9]+' | tr '\n' ' ')
        for isss in $iss    
        do  
                if [[ $isss =~ '[0-9]+' ]]
                then
                  echo "#$isss"
                fi  
        done;

fi

check out this one

Prem Joshi
  • 139
  • 1
  • 7