Arduino Yun run shell command with variable - shell

I need help on this part of a project I am making, I need to run a shell command and pass a variable either string or char to it.
p.runShellCommand("madplay /mnt/sda1/");
Above is my shell command which works, however I want to put a variable after the last slash
p.runShellCommand("madplay /mnt/sda1/variable");
The above code is what I have tried, replacing variable with my variable and didn't seem to work.
I have also tried this which seems to work
String hey = "madplay /mnt/sda1/worldOfTomorrow.mp3";
p.runShellCommand(hey);

It's just string concatenation:
String command= "madplay /mnt/sda1/";
String var = "worldOfTomorrow.mp3";
p.runShellCommand(command+var);
Now, write in var with desired function:
String command= "madplay /mnt/sda1/";
String var = getNameOfFile();
p.runShellCommand(command+var);
...
public String getNameOfFile(){
//code retrieving your desired variable by Serial/SDcard/Ethernet....
}

Related

Jenkins. Inserting environment variable in the file

I have a .env file that contains the following data
API_URL=${API_URL}
API_KEY=${API_KEY}
API_SECRET=${API_SECRET}
Setting environment variables in Jenkins and passing them to the pipeline is clear. But it is not clear how do I replace ${API_URL}, ${API_KEY} & ${API_SECRET} in the .env file with their values in the Jenkins environment variable? Plus, how do I loop through all the Jenkins variables?
This basically requires two steps:
Get all environment variables
Replace values of environment variables in the template (.env) file
Let's start with #2, because it dictates which kind of data #1 must produce.
2. Replace variables in a template
We can use Groovy's SimpleTemplateEngine for this task.
def result = new SimpleTemplateEngine().createTemplate( templateStr ).make( dataMap )
Here templateStr is the template string (content of your .env file) and dataMap must be a Map consisting of string keys and values (the actual values of the environment variables). Getting the template string is trivial (use Jenkins readFile step), reading the environment variables into a Map is slightly more involved.
1. Read environment variables into a Map
I wrote "slightly more involved" because Groovy goodness makes this task quite easy aswell.
#Chris has already shown how to read environment variables into a string. What we need to do is split this string, first into separate lines and then each line into key and value. Fortunately, Groovy provides the member function splitEachLine of the String class, which can do both steps with a single call!
There is a little caveat, because splitEachLine is one of the functions that doesn't behave well in Jenkins pipeline context - it would only return the first line. Moving the critical code into a separate function, annotated with #NonCPS works around this problem.
#NonCPS
Map<String,String> envStrToMap( String envStr ) {
def envMap = [:]
envStr.splitEachLine('=') {
envMap[it[0]] = it[1]
}
return envMap
}
Finally
Now we have all ingredients for letting Jenkins cook us a tasty template soup!
Here is a complete pipeline demo. It uses scripted style, but it should be easy to use in declarative style as well. Just replace node with a script block.
import groovy.text.SimpleTemplateEngine
node {
// TODO: Replace the hardcoded string with:
// def tmp = readFile file: 'yourfile.env'
def tmp = '''\
API_URL=${API_URL}
API_KEY=${API_KEY}
API_SECRET=${API_SECRET}'''
withEnv(['API_URL=http://someurl', 'API_KEY=123', 'API_SECRET=456']) {
def envMap = getEnvMap()
echo "envMap:\n$envMap"
def tmpResolved = new SimpleTemplateEngine().createTemplate( tmp ).make( envMap )
writeFile file: 'test.env', text: tmpResolved.toString()
// Just for demo, to let me see the result
archiveArtifacts artifacts: 'test.env'
}
}
// Read all environment variables into a map.
// Here, #NonCPS must NOT be used, because we are calling a Jenkins step.
Map<String,String> getEnvMap() {
def envStr = sh(script: 'env', returnStdout: true)
return envStrToMap( envStr )
}
// Split a multiline string, where each line consists of key and value separated by '='.
// It is critical to use #NonCPS to make splitEachLine() work!
#NonCPS
Map<String,String> envStrToMap( String envStr ) {
def envMap = [:]
envStr.splitEachLine('=') {
envMap[it[0]] = it[1]
}
return envMap
}
The pipeline creates an artifact "test.env" with this content:
API_URL=http://someurl
API_KEY=123
API_SECRET=456
You can access variables by executing simple shell in scripted pipeline:
def variables = sh(script: 'env|sort', returnStdout: true)
Then programatically in Groovy convert it to list and iterate using each loop.
According to replacing variables, if you're not using any solution which can access env variables then you can use simple text operations like executing sed on that file.

Ansible : how to pass "{{ABC}}" as a string

Under my jinja file i ve this line
- mockString= "{{ABC}}"
My mockString must have the exacte value "{{ABC}}" where the first letter is " , the second is { the third is also { ect...
Now when converting my template file ; it seems that i sees "{{ABC}}" as a variable , where it tries to interpret and change by its value , what is not my purpose.
How may i pass it as a simple string
Suggestions ??
Try passing it like this {{'"{{ABC}}"'}} this should work
you can try like this :
mockString= \"{{ACB}}\"

Extracting part of a string on jenkins pipeline

I am having some trouble with the syntax in my pipeline script.
I am trying to capture everything after the last forward slash "/" and before the last period "." in this string git#github.com:project/access-server-pd.git (access-server-pd)
Here (below) is how I would like to set it up
MYVAR="git#github.com:project/access-server-pd.git"
NAME=${MYVAR%.*} # retain the part before the colon
NAME=${NAME##*/} # retain the part after the last slash
echo $NAME
I have it current set up with triple quotes on the pipeline script:
stage('Git Clone') {
MYVAR="$GIT_REPO"
echo "$MYVAR"
NAME="""${MYVAR%.*}"""
echo "$NAME"
But I am receiving an unexpected token on "." error. How might I write this so that I can get this to work?
UPDATE: This command does the trick:
echo "git#github.com:project/access-server-pd.git" | sed 's#.*/\([^.]*\).*#\1#'
Now I just need to find the proper syntax to create a variable to store that value.
In this case, it looks like using a few Groovy/Java methods on the String can extract the parts.
final beforeColon = url.substring(0, url.indexOf(':')) // git#github.com
final afterLastSlash = url.substring(url.lastIndexOf('/') + 1, url.length()) // project/access-server-pd.git
This uses a few different methods:
public int String.indexOf(String str, int fromIndex)
public String String.substring(int beginIndex, int endIndex)
public int String.length()
public int String.lastIndexOf(String str)
You do need to be careful about the code you use in your pipeline. If it is sandboxed it will run in a protected domain where every invocation is security checked. For example, the whitelist in the Script Security Plugin whitelists all of the calls used above (for example, method java.lang.String lastIndexOf java.lang.String).
Performing String manipulation in your pipeline code is perfectly reasonable as you might make decisions and change your orchestration based on it.

Variable appears to be lost when setting a property in jmeter

I want create a property from a variable. The variables was created by calling a variable from a xpath extraction, then using a substring to then get the last 4 characters. The substring string value is saved to a variable, then set to a property.
When I run the script, the log.info(vars.get("lastcard")); returns the value of the variable. However it then fails to save to a property, because when that property is called(${__property(lastNum)} it will display - ${lastcard}
import org.apache.jmeter.util.JMeterUtils;
import org.apache.commons.lang3;
String tesTe = vars.get("card");
String last4 = tesTe.substring(tesTe.length()-4,tesTe.length());
vars.put("lastcard", String.valueOf(last4));
log.info(vars.get("lastcard"));
${__setProperty(lastNum,${lastcard})};
Any ideas as to what is going on
You should read user manual about scripting:
ensure the script does not use any variable using ${varName}
You should use JSR223 variables vars and props to handle variables and properties. In your case change last line to:
props.put("lastNum", vars.get("lastcard"));
Also you can set variable in shorter way:
vars.put("lastcard", vars.get("card").substring(tesTe.length()-4));
There was 2 changes that need to be made to resolve the issues.
import org.apache.jmeter.util.JMeterUtils;
import org.apache.commons.lang3;
String tesTe = vars.get("card");
String last4 = tesTe.substring(tesTe.length()-4,tesTe.length());
vars.put("lastcard", last4); //Already string therefore no need to use String.valueOf()
log.info(vars.get("lastcard"));
props.put("lastNum",vars.get("lastcard")); //Setup to use props.put instead of set property

Use embedded string as variable name

I have a YAML file that uses the encoding __firstname__ as a placeholder which signifies that an existing method firstname should be used, rather than the literal string in a subsequent process.
I am trying to understand the most ruby way to to do this. Basically, I need to extract the part between the underscores and send it to an object. Here is pseudocode:
variable = '__firstname__'
if variable is prefixed and suffixed with underscores
result = object.send(variable.removeunderscores)
else
result = variable
end
puts result
I was about to write this procedurally like this, but this is the type of thing that I think ruby can less clunkily if only I knew the language better.
What is a clean why to write this?
There's nothing wrong with verbose code if it's clear to read IMO.
I'd do something like this using String#start_with? and String#end_with?:
variable = '__firstname__'
if variable.start_with?("__") && variable.end_with?("__")
result = object.send(variable[2...-2])
else
result = variable
end

Resources