1

I am pretty unexperienced (to put it mildly) when it comes to BASH and Shell scripting, so bear with me:

$ toda=$(date) | echo $toda

gives me: Fr 29 Mai 2020 15:25:19 CEST. So far so good.

datediff is part of the dateutils package and gives back the number of days between to dates:

datediff 2019-12-31 2020-05-29

gives me: 150. Again, so far so good. But:

toda=$(datediff 2019-12-31 2020-05-29) | echo $toda

gives me back: Fr 29 Mai 2020 15:25:19 CEST and not (as expected) 150. In other words it did not assign the datediff result but kept the value from the former operation unchanged. Of course I tried:

anothervarname=$(datediff 2019-12-31 2020-05-29) | echo $anothervarname

which gives back an empty variable (ie a blank line above the prompt). What do I have to do to assign the datediff result from the above example to a variable? Thanks for your help.

Guebert
  • 13

1 Answers1

1

'|' is used to redirect the output of one command to the next command .In your case NO output is produced in the first command bcz its just assigning value to a variable .

What you have to use is : ( try this )

toda=$(date) && echo "$toda"

&& -> executes the trailing command if the first command succeeded only.AND Operator.

  • 1
    Thanks Vignesh that did the trick. I still struggle to understand exactly why this works and piping does not but at least I know now how tp proceed. I upvoted your answer but unfortunately votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score. So gain: Thanks for your help. – Guebert May 29 '20 at 14:04
  • @Guebert : Pleasure.Glad it helps... | will get the output of your toda=$(date) to your next command as input for echo $toda which is nothing(empty) bcz toda=$(date) just assing output of date command to toda variable and output nothing.Thats y... – Stalin Vignesh Kumar May 29 '20 at 14:06
  • Not only does the assignment not write anything to the pipe, but echo does not read from the pipe either. echo writes out its arguments. In addition, the whole line is parsed and substituted before either part of it runs, so the echo arg is set before the assignment happens. – Paul_Pedant May 29 '20 at 15:13
  • yes , correct ,echo does not read from pipe...thanks for notifying me.. – Stalin Vignesh Kumar May 29 '20 at 15:16