Sunday, 28 June 2020

Loop through an array of strings in Bash?

## declare an array variable
declare -a arr=("element1" "element2" "element3")

## now loop through the above array
for i in "${arr[@]}"
do
   echo "$i"
   # or do whatever with individual element of the array
done

# You can access them using echo "${arr[0]}", "${arr[1]}" also

In Bash, how can I check if a string begins with some value?

This snippet on the Advanced Bash Scripting Guide says:

# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.

[[ $a == z* ]]   # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

Create array in loop from number of arguments

You can use the += operator to append to an array.

args=()
for i in "$@"; do
    args+=("$i")
done
echo "${args[@]}"

Run bash command on jenkins pipeline

The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.

So instead, you should format your Groovy like this:

stage('Setting the variables values') {
    steps {
         bash '''#!/bin/bash
                 echo "hello world" 
         '''
    }
}