0

I'm pretty new to bash and and stumbling at this issue.

I have an input file that shows my gpg keys and their expiration dates. I'm using a while-read loop to attempt to read the file and parse out the two fields I need...

#!/bin/bash
input="/home/currentkeys.txt"
checkdate=`date -d "+30 days" +%s`
while IFS= read -r line
do
 keydate=`awk '{print $4}'`
 printf "%s\n" $keydate
 keyuid=`awk '{print $1}'`
 printf "%s\n" $keyuid
done <"$input"

But when I run the script, it's only printing the $keydates to screen...

bash-4.2$ ./keyexpiryreport.sh
2020-08-08
2022-09-10
2022-09-10
2022-09-17
...

eventually I'm going to use $checkdate to compare against the $keydate to see if we're getting close to the key expiring, but if I can't get the second variable to work I'm kinda stuck here...

  • Do yourself a favor and don't do this in bash. It's certainly possible, but this is better suited for python/perl/ruby or really any general purpose programming language with proper string libraries. – Z4-tier Dec 29 '20 at 21:16
  • What is the purpose of `checkdate`? – Cyrus Dec 29 '20 at 21:26
  • Instead of using `read -r line`, use `read -r col1 col2 col3 col4 rest` -- that way `read` itself splits your data into variables. – Charles Duffy Dec 29 '20 at 21:44
  • 1
    @Z4-tier, bash _has_ plenty of general-purpose string-management operations built-in. There's no reason to use an external program like `awk` or `sed` for any of this -- see [BashFAQ #100](https://mywiki.wooledge.org/BashFAQ/100), and the bash-hackers page on [parameter expansion](https://wiki.bash-hackers.org/syntax/pe). I don't object to folks moving to a more capable language when appropriate, but what the OP is doing here is _well_ inside the shell's native capabilities. – Charles Duffy Dec 29 '20 at 21:45
  • @CharlesDuffy The string manipulation operations in bash are confusing and use unintuitive syntax, and anything beyond the most basic operations ends up using sed/awk/expr or some other program as a crutch (but not echo... never echo). I am making the assumption that OP intends to do more than just what is included in the post, but if this really is the extent of what this script is going to do, then bash is probably ok. – Z4-tier Dec 29 '20 at 22:10
  • There should never be a reason to use `expr` in modern scripts -- for most purposes POSIX mandates built-in equivalents to its functionality (and has since the original early-1990s release of POSIX.2), and the few remaining cases are covered by ksh extensions that bash, zsh, and everyone else has adopted (but which POSIX didn't roll in). – Charles Duffy Dec 30 '20 at 00:53

1 Answers1

2

Without a example of you file i don't know if it's gonna work. but you can do something like this for cleaning the script.

while read keyuid _ _ keydate _; do 
  echo "$keydate" 
  echo "$keyuid"
done <"$file"
Dr Claw
  • 636
  • 4
  • 15