replace string in class bash and azuredevops (ios xamarin pipeline) - bash

I am trying to write a bash script to change a string in a class for my azure devops pipeline.But cannot make it work.
Copied the script from
https://github.com/Microsoft/appcenter-build-scripts-examples/blob/master/xamarin/app-constants/appcenter-pre-build.sh
my bash attempt:
Added a bash task (inline script)
Created an env variable API_URL with value ="https://production.com/api"
My Class to change
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://production.com/api";
public const string AnotherOne="AAA";
}
}
My script
if [ ! -n "$API_URL" ]
then
echo "You need define the API_URL variable"
exit
fi
APP_CONSTANT_FILE=$(Build.SourcesDirectory)/MyProject/Core/AppConstant.cs
if [ -e "$APP_CONSTANT_FILE" ]
then
echo "Updating ApiUrl to $API_URL in AppConstant.cs"
sed -i '' 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
echo "File content:"
cat $APP_CONSTANT_FILE
fi
why does my variable not change? many thanks

Your script is correct and will get desired output, only remove the dual apostrophes after sed -i:
sed -i 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
However I would also change regexp at least to this, since . (dot) is reserved as any character in regexp:
sed -i 's#ApiUrl = "[a-z:\./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
Or even to this (in order to take whatever characters between quotes):
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
Test:
$ cat > developer9969.txt
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://production.com/api";
}
}
API_URL='https://kubator.com/'
APP_CONSTANT_FILE='./developer9969.txt'
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
$ cat $APP_CONSTANT_FILE
namespace Core
{
public class AppConstant
{
public const string ApiUrl = "https://kubator.com/";
}
}

Related

How to print a value in single line using shell command?

I have written a shell script in a groovy function which should return the the output (in a single line) as abcd-def-chart but, I am getting the output as shown below in 2 different lines:
abcd-def
-chart
My groovy code:
String getChartName(Map configuration = [:]) {
if (configuration.chartName != null) {
return configuration.chartName
}
chartName = ""
if (configuration.buildSystem == 'maven') {
chartName = getMavenProjectName() + "-chart"
}
echo "chartName: ${chartName}"
return chartName
}
String getMavenProjectName() {
echo "inside getMavenProjectName +++++++"
def mavenChartName = sh returnStdout:true, script: '''
#!/bin/bash
GIT_LOG=$(env -i git config --get remote.origin.url)
basename "$GIT_LOG" .git; '''
echo "mavenChartName: ${mavenChartName}"
return mavenChartName
}

How to assign a shell command output as value to envrionment variable?

Below is my pipeline snippet and I am trying to assign RSTATE variable a value at run time. This value is basically stored in a text file but we need to grep and cut it. So a shell command output should be its value.
pipeline
{
agent any
environment
{
RSTATE = 'R4C'
ISO_REV = 'TA'
BuildSource = '18'
}
stages
{
stage('get Rstate')
{
echo env.RSTATE
}
}
}
I am trying to assign RSTATE value like:
RSTATE = sh ( script: 'grep RSTATE /proj/MM/scm/com/iv_build/mm18_1/rstate/next_rstate.txt
|cut -d "=" -f2', returnStdout: true).trim()
But this is not working.
I also tried to run a shell script but that also not works. Only hard coded value is working. Please suggest.
I tested and worksm you need to validate if your script return the value you want.
pipeline
{
agent any
environment
{
RSTATE = 'R4C'
ISO_REV = 'TA'
BuildSource = '18'
}
stages
{
stage('get Rstate')
{
steps {
script {
def RSTATE2 = sh ( script: 'echo \${RSTATE}', returnStdout: true).trim()
echo env.RSTATE
echo RSTATE2
}
}
}
}
}

Passing bash variable into inline perl script

Reference the 2nd to last line in my script. For some reason Perl is not able to access the variable $perlPort how can I fix this? Note: $perlPort is a bash variable location before my perl script
perl -e '
{
package MyWebServer;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
my %dispatch = (
"/" => \&resp_hello,
);
sub handle_request {
my $self = shift;
my $cgi = shift;
my $path = $cgi->path_info();
my $handler = $dispatch{$path};
if (ref($handler) eq "CODE") {
print "HTTP/1.0 200 OK\r\n";
$handler->($cgi);
} else {
print "HTTP/1.0 404 Not found\r\n";
print $cgi->header,
$cgi->start_html("Not found"),
$cgi->h1("Not found"),
$cgi->end_html;
}
}
sub resp_hello {
my $cgi = shift; # CGI.pm object
return if !ref $cgi;
my $who = $cgi->param("name");
print $cgi->header,
$cgi->start_html("Hello"),
$cgi->h1("Hello Perl"),
$cgi->end_html;
}
}
my $pid = MyWebServer->new($perlPort)->background();
print "Use 'kill $pid' to stop server.\n";'
export perlPort
perl -e '
...
my $pid = MyWebServer->new($ENV{perlPort})->background();
'
You can use -s switch to pass variables. See http://perldoc.perl.org/perlrun.html
perl -se '
...
my $pid = MyWebBrowser->new($perlPort)->background();
...' -- -perlPort="$perlPort"
You can still pass command line arguments to your script. Replace $perlPort with $ARGV[0], then call you script as
perl -e $' ...
my $pid = MyWebServer->new($ARGV[0])->background();
print "Use \'kill $pid\' to stop server.\n";' "$perlPort"
Note the other problem: You can't include single quotes inside a single-quoted string in bash. You can work around this by using a $'...'-quoted string as the argument to Perl, which can contain escaped single quotes. If your script doesn't need to read from standard input, it would be a better idea to have perl read from a here-document instead.
perl <<'EOF' "$perlPort"
{
package MyWebServer;
use HTTP::Server::Simple::CGI;
...
my $pid = MyWebServer->new($ARGV[0])->background();
print "Use 'kill $pid' to stop server.\n";
EOF
The best idea is to simply use a script file instead of trying to construct the script on the command line.
perl -e '
...
my $pid = MyWebServer->new('$perlPort')->background();
...

Network Monitor: Don't Show Same Line Immediately Twice [duplicate]

I am writing a network monitoring script in bash. The base command I am using is ettercap -T -M ARP -i en1 // //. Then I pipe egrep --color 'Host:|GET' into it.
A sample output I am getting looks like this:
GET /images/srpr/logo11w.png HTTP/1.1.
Host: www.google.com.
GET /en-us/us/products HTTP/1.1.
Host: www.caselogic.com.
My desired output is this:
Title: logo11w.png
URL: www.google.com/images/srpr/logo11w.png HTTP/1.1.
Title: Products - Case Logic
URL: www.caselogic.com/en-us/us/products
Things to notice: HTTP/1.1. and the . at the end of the host are gone. They also are formed into one URL and there is a blank line after each Title/URL listing. I attempted forming them into one URL by parsing the commands output into a variable with
var=`sudo ettercap -T -M ARP -i en1 // // | egrep --color 'Host:|GET'` | echo $var
but obviously that doesn't work because the input to the variable is a command the isn't done until the user requests a stop (CTRL + C).
To get the title of an HTML page, I use the command wget -qO- 'https://url.goes/here' | perl -l -0777 -ne 'print $1 if /<title.*?>\s*(.*?)\s*<\/title/si'. If it is something that doesn't have a title, such as an image, no title is fine.
Any help is greatly appreciated, and sorry if what I wrote is hard to read, feel free to ask questions.
Try this:
title_host.pl
#!/usr/bin/env perl
use warnings;
use strict;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
my ($get,$host,$title);
while (<>) {
if (m|^GET (\S+) |) {
$get = $1;
} elsif ( m|^Host: (\S+)\.| ) {
$host = $1;
} else {
# Unrecognized line...reset
$get = $host = $title = '';
}
if ($get and $host) {
my ($title) = $get =~ m|^.*\/(.+?)$|; # default title
my $url = 'http://' . $host . $get;
$mech->get($url);
if ($mech->success) {
# HTML may have title, images will not
$title = $mech->title() || $title;
}
print "Title: $title\n";
print "URL: $url\n";
print "\n";
$get = $host = $title = '';
}
}
input
GET /images/srpr/logo11w.png HTTP/1.1.
Host: www.google.com.
GET /en-us/us/products HTTP/1.1.
Host: www.caselogic.com.
now just pipe your input into the perl script:
cat input | perl title_host.pl
output:
Title: logo11w.png
URL: http://www.google.com/images/srpr/logo11w.png
Title: Products - Case Logic
URL: https://www.caselogic.com/en-us/us/products

How to print a character using Shell script

Below is my script that acquire the MAC of the machine and store within a config file.
My problem is that within each line have the character " " and it dont print it inside the file, how can I write the file using " "
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
echo "
view.sslVerificationMode = *3*
view.autoConnectDesktop = *TRUE*
view.autoConnectBroker = *TRUE*
view.kioskLogin = *TRUE*
view.nonInteractive = *TRUE*
view.fullScreen = *TRUE*
view.nomenubar = *TRUE*
view.defaultBroker = *viewcs*
view.defaultUser = *CM-${MAC//:/_}*
" > /etc/vmware/view-mandatory-config;
sed -i 's/*/"/g' /etc/vmware/view-mandatory-config
with cat and a here-doc you can use multi-line input without escaping charaters
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
cat << EOT > /etc/vmware/view-mandatory-config
view.sslVerificationMode = "3"
view.autoConnectDesktop = "TRUE"
view.autoConnectBroker = "TRUE"
view.kioskLogin = "TRUE"
view.nonInteractive = "TRUE"
view.fullScreen = "TRUE"
view.nomenubar = "TRUE"
view.defaultBroker = "viewcs"
view.defaultUser = "CM-${MAC//:/_}"
EOT
cat will relay the stdin input generated by the here document to stdout, thus enabling redirection to a file
Simply escape double-quotes within the outer double-quotes by putting a backslash in front of them:
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
echo "
view.sslVerificationMode = \"3\"
view.autoConnectDesktop = \"TRUE\"
view.autoConnectBroker = \"TRUE\"
view.kioskLogin = \"TRUE\"
view.nonInteractive = \"TRUE\"
view.fullScreen = \"TRUE\"
view.nomenubar = \"TRUE\"
view.defaultBroker = \"viewcs\"
view.defaultUser = \"CM-${MAC//:/_}\"
" > /etc/vmware/view-mandatory-config

Resources