-3

The intention of my script is to print the users who have inactive days of more than 30. This is my script:

#!/bin/bash

max=30
grep -E ^[^:]+:[^\!*] /etc/shadow | awk -F: '{print $1" "$7}' | while read user days
do 
    if [ $days -gt $max ]
    then
        echo $user
        echo $days
    fi
done

I created 2 users, test and test2 each with 30 days and 50 days inactivity respectively. This script returns me both when I only need to print test2 with 50 days of inactivity.

1 Answers1

0

I think you are making this more complicated than needed.

Since you already have awk in your pipe, that can replace grep and compare to max.

Simple example.

Given:

cat file
dawg 2 3 4 5 6 45
boosh 2 3 4 5 6 25

You can do:

max=30
awk -v max="$max" '$7>max{print $1, $7}' shadow
dawg 2 3 4 5 6 45

I left out the grep portion but you can either keep that as a pipe (if it is working) or integrate into the awk.


If you want to compare two integers in Bash, you either need to use the correct test, which is (( arithmetic context ))

$ (( 1>2 )); echo $?  
1
$ (( 10>2 )); echo $? 
0
# 0 means TRUE

or the correct operator which is [ -gt ]:

$ [ 10 -gt 2 ]; echo $? 
0
$ [ 1 -gt 2 ]; echo $?  
1

But if you use > inside of [[ .. ]] you are actually comparing strings and may be the wrong answer:

$ [[ 10 < 2 ]]; echo $?  
0                      # '0' means 'true' 10 < 2 only as strings

And you must use double [[ .. ]] to use > otherwise it is the redirection operator. (Thanks M. Nejat Aydin ...)

dawg
  • 98,345
  • 23
  • 131
  • 206
  • 1
    `But if you use > inside of [ .. ] you are actually comparing strings`: No. Unquoted `>` is redirection operator inside `[...]`. It doesn't compare anything. – M. Nejat Aydin Jan 25 '22 at 15:37
  • Drak! You are right. Edit made. I have use `[[ ... ]]` for so long I forgot that... – dawg Jan 25 '22 at 16:54