5

Suppose you had two commands:

First command

let foo=2+2
echo $foo
4

Second command

date "%s"
1377107324

How would you combine them?


Attempt 1.

echo The epoch time is: `date +%s` in 100 seconds the time \
     will be: `let future={date +%s}+100` $future

Attempt 2.

echo The epoch time is: `date +%s` in 100 seconds the time \
     will be: `let future=(date +%s)+100` $future

Plus about 30 other similar attempts

spuder
  • 18,053

3 Answers3

6

This is an important reason to use the $( ) instead of ` ` (see What's the difference between $(stuff) and `stuff`?)

If you nest it like this, you don't even need let or a variable:

$ echo $(date +%s) " "  $(( $(date +%s)+100 ))
1377110185   1377110285
Bernhard
  • 12,272
  • 1
    Actually, you can change $( ) back to \ `` and it will do the same thing. What you actually did is change let to $(( )). – cjm Aug 21 '13 at 18:42
  • 1
    @cjm If you try it with backticks, you will cry eventually :) – Bernhard Aug 21 '13 at 18:45
3

You need to add an $ before the parenthesis and also to export $future:

$ echo The epoch time is: `date +%s` in 100 seconds the time  will be: \
 `let future=$(date +%s)+100; export future` $future
The epoch time is: 1377110177 in 100 seconds the time will be: 1377110252

Variables are not shared between bash instances. Each time you run a $() (or backticks) command, any variables defined within it will not be accessible to the parent shell:

$ foo=$(echo 12);
$ echo $foo
12
$ foo=(echo 12; foo=0)
$ echo $foo
$ echo $foo
12

As you can see, although you set foo to 0 within the $() subshell, that value is not exported to the parent shell.

terdon
  • 242,166
3

Declare the variables, export them and then use them as you like:

date=$( date +%s )
future=$(( $date + 100 ))

echo "The epoch time is: $date in 100 seconds time will be: $future"

which gives:

The epoch time is: 1377110185 in 100 seconds time will be: 1377110285

And you can continue to use those values:

echo "which is the same as $(( $date + 100 ))"  

which gives:

which is the same as 1377110285

Note that if these are in a script they do not need to be exported, only on the command line do you need to export them to be used in subsequent commands.

Or you can leave the variables out all together:

echo "The epoch time is: $(date +%s) in 100 seconds the time will be: $(( $(date +%s)+100 ))"

Note that ``date +%s\ and $( date +%s ) are pretty much similar, but that's another topic best covered in this Answer

Drav Sloan
  • 14,345
  • 4
  • 45
  • 43