1

I have a pipe condition as:

if true | openssl s_client -connect $SSL_URL | openssl x509 -noout -dates -checkend 0 | grep 'notAfter'; 

now I want to take the value returned from grep 'notAfter' in a shell variable how can I do that.

I have tried this

if true | openssl s_client -connect $SSL_URL | openssl x509 -noout -dates -checkend 0 | A=$("grep 'notAfter'");

but it is not working.

User 101
  • 1,351
  • 3
  • 12
  • 18
  • Possible duplicate of [How to set a variable to the output from a command in Bash?](https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash) – Sundeep Dec 01 '17 at 09:31
  • see also http://mywiki.wooledge.org/BashFAQ/002 – Sundeep Dec 01 '17 at 09:32

1 Answers1

2

You are probably looking for

if A=$(openssl s_client -connect "$SSL_URL" </dev/null | 
    openssl x509 -noout -dates -checkend 0 |
    grep 'notAfter')
then
    :

This assigns the output of the pipeline to the variable A, and checks the result code from grep; if it succeeded (i.e. a match was found) the then branch of the conditional is taken.

The pipe from true is odd and unconventional; I imagine the purpose of that was to make sure it doesn't receive anything useful on standard input. The usual way to do that is to redirect stdin to come from /dev/null so I'm doing that instead.

Finally, notice also the proper quoting of the variable. If SSL_URL would happen to contain a shell metacharacter, you would get an error or in the worst case a security problem.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • its is giving in output `notAfter=Feb 16 10:47:00 2018 GMT` but I want only `Feb 16 10:47:00 2018 GMT` – User 101 Dec 01 '17 at 10:11
  • `and checks the result code from grep` can you explain what you mean by this – User 101 Dec 01 '17 at 10:43
  • Every Unix command returns a result code (exit code) which is either zero to signify success, or nonzero to signify an error. The exact codes will often be documented on the manual page, but some documenters are sloppy. The job of `if` (and the other flow control statements in the shell -- `while` and `until`) is to run a command and examine its exit code. This is distinct from what the command prints. You can examine the result of any command with `echo $?` (but notice that `cmd; if [ $? = 0 ]; then` is an antipattern -- the proper way to write that is nearly always simply `if cmd; then`). – tripleee Dec 01 '17 at 10:45
  • The exit code from `variable=$(command)` is the exit code from `command` -- this is slightly obscure, but sometimes useful. And always, the exit code from a pipeline is the exit code from the last command in the pipeline (though some shells allow you to examine the individual commands in the pipeline independently; in Bash, see `PIPESTATUS`). – tripleee Dec 01 '17 at 10:48