Search code examples
bashperl

How do I get a SECONDS variable in Perl from bash?


How do I display basic variables like SECONDS inside Perl while running command in bash?

perl -e 'system(bash -c echo $SECONDS)'

It displays nothing at all. I have no access to the bash variables, but I am running a Perl command in bash.


Solution

  • A bash variable need be exported so that a Perl program, executed in that same bash process, can see it. Then you can use it in Perl as an environment variable, or in a subshell

    echo $SECONDS                                    # 14  (newly opened terminal)
    export SECONDS
    
    perl -wE'say $ENV{SECONDS}'                      # 23
    
    perl -wE'system "bash", "-c", "echo \$SECONDS"'  # 23
    

    Note that the $ character need be escaped otherwise the Perl program will consider the $SECONDS to be a variable of its own. and will try to evaluate it (to no avail) before it passes arguments to system for a shell that it starts.


    The question was raised of how to pass this only to that one program. Then pass the value as a command-line argument to the Perl program? See how to pass shell variables to Perl one-liners for example here.

    Yet another way to make this value available only to the invoked program, contributed by Cyrus in a comment, is

    SECONDS=$SECONDS perl -wE'say $ENV{SECONDS}'
    

    Also, now once a new variable is introduced one can name it more suitably for the Perl program, since it won't anymore behave like the bash's SECONDS. Like

    SHELL_ELAPSED=$SECONDS perl -wE'say $ENV{SHELL_ELAPSED}'