0

I have this script which works fine

#!/bin/bash
if [ $# -lt 1 ]
then
  echo "USAGE: `basename $0` username"
  exit 1
fi

logins=`last | grep $1`
times=`echo "$logins" | awk '{print $10}'`
timesCleared=`echo "$times" | sed -e 's/(//' -e 's/)//'`
minutes=`echo "$timesCleared" | awk -F: '{ print $1*60+$2}'`
total=0
for m in $minutes
do
  total=$(( $total + $m ))
done

echo $total > out.txt
cat out.txt

but, for an example, when i try this command in the interactive shell it doesn't work ( echo $minutes gives a different output):

echo "in 02:16 00:28 00:16 00:25 02:44 00:09" | awk -F: '{ print $1*60+$2;}'

it prints 16

if i write echo $minutes in the scripts it gives me the right output:

0 136 28 16 25 164 9

Does anyone know why is this?

3
  • Looks like there oughta be some escaping.... If it's not with the dollar signs, then it's with the math operators, + - * /. Commented Jan 17, 2016 at 17:07
  • in does not make sense as a number, so is evaluated as zero. (Yes, there is a numeric suffix, but this is what's going on here.) Commented Jan 17, 2016 at 17:19
  • Also, some of the lines I'm getting contain strings like 3+23:27. Commented Jan 17, 2016 at 17:21

2 Answers 2

2

The variables in your script contain newlines, which are important. What is being sent to awk in the line which assigns to the variable minutes is not

in 02:16 00:28 00:16 00:25 02:44 00:09

as in your command-line, but rather

in
02:16
00:28
00:16
00:25
02:44
00:09

In the first case, awk sees $1 as in 02 and $2 as 16 00. In the second case, it works on each line individually. When awk converts a string to a number, it uses only the first characters of the string; if it does not find a number at the beginning (as with the string in 02), it converts it to 0 without any error message.

You can use the RS awk pseudo-variable to set the record separator to a space:

echo "in 02:16 00:28 00:16 00:25 02:44 00:09" |
    awk -F: -v RS=' ' '{ print $1*60+$2;}'

Alternatively, you could echo the string with newlines:

echo "in
02:16
00:28
00:16
00:25
02:44
00:09" | awk -F: '{ print $1*60+$2;}'
Sign up to request clarification or add additional context in comments.

Comments

2

The string you echo in the script is newline-separated, not space-separated; so the command you tried interactively is not doing the same thing.

To reproduce what's going on in the script, try

echo "in 02:16 00:28 00:16 00:25 02:44 00:09" |
tr ' ' '\n' |
awk -F: '{ print $1*60+$2;}'

1 Comment

Yes, i suspected it might be the formatting. This works :)

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.