Perl script shows different behavior inside cron job - perl

I'm executing the following commands in a perl script.
#!/usr/bin/perl
my $MPSTAT="/usr/bin/mpstat";
my $GREP="/bin/grep";
my $FREE = "/usr/bin/free";
my $AWK = "/bin/awk";
my $cpu = `$MPSTAT | $GREP all | $AWK '{print (100 - \$12)}'`;
print "CPU is $cpu";
When I run this perl script manually it's getting executed properly and providing the proper CPU Usage in % (100 - Idle CPU).
But when I execute it as a cronjob it always prints 100 & it appears that $12 of awk is getting the value of 0. Any pointers on why it's behaving differently in cron would be helpful.

The main differences between running as a child of cron are:
The user ID might be different (root vs normal user)
The environment is nearly empty, at least pretty different
The second part often means that programs might output in a different language or number format due to the values of the LANG and LC_* environment variables which might be set for the normal user but not when run under cron (or vice versa).

Found the solution using the hint provided by #WinnieNicklaus
mpstat is giving different results in cron.
Normal Execution:
04:53:18 PM all 49.51 0.00 4.79 2.67 0.02 0.34 0.00 0.00 42.68
Inside Cron:
16:54:01 all 49.51 0.00 4.79 2.67 0.02 0.34 0.00 0.00 42.68
Since PM is not getting printed inside cron, when changed the argument for awk as $11 instead of $12 it started working.

Related

INI file editing, Save format

So i have a working code. i just learned about this today but am wondering if there is a way to save the formatting. (found it on here btw).
$ini = Get-IniContent c:\temp\ini.ini
$ini["posscreen"]["BitmapFile"] = "C:\Temp\FileC.bmp"
$ini | Out-IniFile -FilePath c:\temp\ini2.ini
This is how it looks normally:
[ShapePageFnt]
Position=1.73 -2.76 -15.00
Scale=0.35 0.36 0.38
ZoneDepth=0
StringLength=9600
Font=VerdanaBold
Color=0xFF000000
Kerning=0.270000
String=1/10
StringAlignment=Left
[sgcArialBlack]
FontFile=ArialBlack.png
DataFile=ArialBlack.ftd
StringLength=0
StringStack=0
StringAlignment=Center
Kerning=0.25
Color=0xFF00AAFF
Position=0 0 -1000
Dimension=1 1
Scale=1 1 1
String=
[sgcXtraLabel]
Position=-3.25 -5.61 -15.00
Dimension=1.00 1.00
Scale=0.33 0.33 0.33
ZoneDepth=-101
StringLength=20
Font=VerdanaBold
Color=0xFFFFFFFF
String=Xtra Games
StringAlignment=Center
After running the code:
[ShapePageFnt]
Position=1.73 -2.76 -15.00
Scale=0.35 0.36 0.38
ZoneDepth=0
StringLength=9600
Font=VerdanaBold
Color=0xFF000000
Kerning=0.270000
String=1/10
StringAlignment=Left
[sgcArialBlack]
FontFile=ArialBlack.png
DataFile=ArialBlack.ftd
StringLength=0
StringStack=0
StringAlignment=Center
Kerning=0.25
Color=0xFF00AAFF
Position=0 0 -1000
Dimension=1 1
Scale=1 1 1
String=
[sgcXtraLabel]
Position=-3.25 -5.61 -15.00
Dimension=1.00 1.00
Scale=0.33 0.33 0.33
ZoneDepth=-101
StringLength=20
Font=VerdanaBold
Color=0xFFFFFFFF
String=Xtra Games
StringAlignment=Center
Any help would be appreciated.
** i tried -format and -table just for kicks and didn't do anything but pop up errors.**
Is there a /? for stuff in power shell to check if these conditions are even available?
End goal: to have the code ran and have it output the same way it inputs with the spaces. (the code replaces a set item in the .ini)
I downloaded the script and had a look at the parameters for the Out-IniFile function. I found two switch parameters there:
Pretty which adds an extra linebreak between Sections
Loose which adds spaces around the equal sign when writing the key = value
To use them, your command to write the ini file would be:
$ini | Out-IniFile -FilePath c:\temp\ini2.ini -Pretty -Loose
The author of that script forgot to add descriptions of the parameters in the comment-based help info, so that's why Get-Help didn't show it..
I am unable to comment on the other answer, as I don't have enough reputation points.
#Theo answer is correct; with the exception that the 2 parameters are indeed documented:
https://github.com/lipkau/PsIni/blob/master/PSIni/Functions/Out-IniFile.ps1#L98-L106
I ♥ PS> help Out-IniFile -Parameter pretty, loose
-Pretty [<SwitchParameter>]
Writes the file as "pretty" as possible
Adds an extra linebreak between Sections
Required? false
Position? named
Default value False
Accept pipeline input? false
Accept wildcard characters? false
-Loose [<SwitchParameter>]
Adds spaces around the equal sign when writing the key = value
Required? false
Position? named
Default value False
Accept pipeline input? false
Accept wildcard characters? false
Also, the git repository of that module is https://github.com/lipkau/PsIni.
You can create issues there for missing functionality or general questions

Tcl scripting using grep,sed

I have to find a particular string first, then i need to pick up a value in that string, which is changing aftrr every run. How can i do this.
Stage pro begin_time { size is 54mb and 3 sec }
Stage pro1 begin_time {.....}
I have very big file. I have to specifically look for begin_time string first then look for its value and store it somewhere. How can i do this.
I have tried it using grep but i don't know how to store value of 3 here. Similarly i have many cases here, how can i handle this situation
Thanks for the reply. I want to store it as value 3 with respect to pro, then some other value corresponding to pro1. Second, time mentioned here is a start time. I have same information for each of the stage pro,pro1 but with an end time. I have to extract end time as well. Then i have to caluculate net time elapsed, i.e. time between start time and end time
cat aaa
Stage pro begin_time { size is 54mb and 3 sec }
Stage pro1 begin_time {.....}
cat aaa |awk '$3=="begin_time" {print $9}' |grep .
3
if you wish to store it :
var=$(cat aaa |awk '$3=="begin_time" {print $9}' |grep .)
echo $var
3
If you wish to map pro with 3 then,
cat aaa | awk '$3=="begin_time" {print $2,$9}' |grep .
pro 3

Calculating seconds since the Unix Epoch when there is no +"%s" option for the 'date' command available

I wanted to calculate the seconds since the Unix Epoch (1970-01-01 00:00:00). Usually I would use
date +"%s"
Now, on my system the +"%s" option is not available but I easily got around using some other 'date' options and parsed it using bc:
date -u +"scale=0;(((((%Y-1970)*365.2425+%j)*24+%H)*60+%M)*60+%S)/1" | bc
This is short for
years = year_now - 1970
days = years * 365.2425 + day_of_year_now
hours = days * 24 + hour_now
minutes = hours * 60 + minute_now
seconds = minutes * 60 + second_now
So far so good. Then I discovered that the result of this calculation does not match with the result of the +"%s" option. I needed to add a magic number:
date -u +"scale=0;(((((%Y-1970)*365.2425+%j)*24+%H)*60+%M)*60+%S-36936)/1" | bc
Why?
Additionally, several months later, this magic number has changed from -36936 to -99792.
Why?
I'm sure something is wrong with my maths. I do not need better solutions in other script languages but I'd appreciate if somebody could correct my maths, please. Maybe someone has the source code for date and could show me its internal algorithm for +"%s" ... ?
Here is a POSIX way that should then work on all Unix and Unix like systems:
awk 'BEGIN {srand();print srand()}'
If you use ksh93, this should also work:
printf "%(%s)T\n"
Most system will have perl installed:
perl -le 'print time'

What am I doing wrong while importing the following data into sas

I am trying to import certain data into my SAS datset using this piece of code:
Data Names_And_More;
Infile 'C:\Users\Admin\Desktop\Torrent Downloads\SAS 9.1.3 Portable\Names_and_More.txt';
Input Name & $20.
Phone : $20.
Height & $10.
Mixed & $10.;
run;
The data in the file is as below:
Roger Cody (908)782-1234 5ft. 10in. 50 1/8
Thomas Jefferson (315)848-8484 6ft. 1in. 23 1/2
Marco Polo (800)123-4567 5Ft. 6in. 40
Brian Watson (518)355-1766 5ft. 10in 89 3/4
Michael DeMarco (445)232-2233 6ft. 76 1/3
I have been trying to learn SAS and while going through Ron Cody's book Learning SAS by example,I found to import the kind of data above, we can use 'the ampersand (&) informat modifier. The ampersand, like the colon,says to use the supplied informat, but the delimiter is now two or more blanks instead of just one.' (Ron's words, not mine). However, while importing this the result (dataset) is as follows:
Name Phone Height Mixed
Roger Cody (908)782- Thomas Jefferson Marco Polo
Also, for further details the SAS log is as follows:
419 Data Names_And_More;
420 Infile 'C:\Users\Admin\Desktop\Torrent Downloads\SAS 9.1.3 Portable\Names_and_More.txt';
421 Input Name & $20.
422 Phone : $20.
423 Height & $10.
424 Mixed & $10.
425 ;run;
NOTE:
The infile 'C:\Users\Admin\Desktop\Torrent Downloads\SAS 9.1.3 Portable\Names_and_More.txt' is:
File Name=C:\Users\Admin\Desktop\Torrent Downloads\SAS 9.1.3 Portable\Names_and_More.txt,
RECFM=V,LRECL=256
NOTE:
LOST CARD.
Name=Brian Watson (518)35 Phone=Michael Height=DeMarco (4 Mixed= ERROR=1 N=2
NOTE: 5 records were read from the infile 'C:\Users\Admin\Desktop\Torrent Downloads\SAS 9.1.3
Portable\Names_and_More.txt'.
The minimum record length was 37.
The maximum record length was 47.
NOTE: SAS went to a new line when INPUT statement reached past the end of a line.
NOTE: The data set WORK.NAMES_AND_MORE has 1 observations and 4 variables.
NOTE: DATA statement used (Total process time):
real time 0.17 seconds
cpu time 0.14 seconds
I am looking for some help with this one. It'd be great if someone can explain what exactly is happening, what am I doing wrong and how to correct this error.
Thanks
The answer is in the explanation in Ron Cody's book. & means you need two spaces to separate varaibles; so you need a second space after the name (and other fields with &).
Wrong:
Roger Cody (908)782-1234 5ft. 10in. 50 1/8
Right:
Roger Cody (908)782-1234 5ft. 10in. 50 1/8

How can I encode a string for HTML?

I'm looking for a simple way to HTML encode a string/object in Perl. The fewer additional packages used the better.
HTML::Entities is your friend here.
use HTML::Entities;
my $encoded = encode_entities( "foo & bar & <baz>" );
When this question was first answered, HTML::Entities was the module most people probably used. It's pure Perl and by default will escape the HTML reserved characters ><'"& and wide characters.
Recently, HTML::Escape showed up. It has both XS and pure Perl. If you're using the XS version, it's about ten times faster than HTML::Entities. However, it only escapes ><'"& and has no way to change the defaults. Here's the difference with the XS version:
Benchmark: timing 10000 iterations of html_entities, html_escape...
html_entities: 14 wallclock secs (14.09 usr + 0.01 sys = 14.10 CPU) # 709.22/s (n=10000)
html_escape: 1 wallclock secs ( 0.68 usr + 0.00 sys = 0.68 CPU) # 14705.88/s (n=10000)
And here's the fair fight with pure Perl versions on each side:
Benchmark: timing 10000 iterations of html_entities, html_escape...
html_entities: 14 wallclock secs (13.79 usr + 0.01 sys = 13.80 CPU) # 724.64/s (n=10000)
html_escape: 7 wallclock secs ( 7.57 usr + 0.01 sys = 7.58 CPU) # 1319.26/s (n=10000)
You can get these benchmarks in Surveyor::Benchmark::HTMLEntities. I explain how I distribute benchmarks using Surveyor::App.
Which do you need to encode, a string or an object? If it's just a string, then you should just have to worry about encoding issues such as UTF-8, and CGI::escape will probably do the trick for you. If it's an object, you'll need to serialize it first, which opens up a whole new set of issues, but you might want to consider JSON-encoding it.
PS. Although since I can't find any recent documentation on this method (it's actually imported from CGI::Util and is marked as "internal"), you should probably use escapeHTML() as daxim points out in his comment: http://search.cpan.org/perldoc?CGI#AUTOESCAPING_HTML