Initiating a docker swarm and getting the current docker swarm token

Creating a docker swarm cluster:

The docker swarm can be created by using the following command:

The syntax is defined as follows:

docker swarm init --advertise-addr [available interface IP adress]

The –advertise-addr is used to explicitly define the docker swarm advertise ip. If you have a single interface this option will not be needed but will be real handy if you have more than 1 active public accessible interfaces.
Let us initialize our docker swarm environment.

[vamshi@docker-swarm ~]$ docker swarm init --advertise-addr 10.100.0.20
Swarm initialized: current node (nodeidofmastercdq7nmmq3kcmb5l85k2e) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join \
    --token SWMTKN-1-verylongstringofcharactercontainingthedockerswarmjoinstring-70bouyqwhfgdcgtw6o0fw6wup \
    10.100.0.20:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

The docker swarm creation can be viewed from the docker info command as follows:

[vamshi@docker-swarm ~]$ docker info | grep -C 2 Swarm
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: active
 NodeID: nodeidofmastercdq7nmmq3kcmb5l85k2e
 Is Manager: true

The docker swarm explicitly uses the overlay and macvlan to enable the interhost network connectivity between the container over a swarm network

How to get the docker swarm join token:

This command can come in very handy when you forgot your docker swarm token and you need to join a new docker node to this docker swarm cluster.

[vamshi@docker-swarm ~]$ docker swarm join-token manager -q
SWMTKN-1-verylongstringofcharactercontainingthedockerswarmjoinstring-70bouyqwhfgdcgtw6o0fw6wup

How can I get token to join docker Swarm?

Run the command from the output on the worker to join the swarm: $ docker swarm join \ –token SWMTKN-1-49nj1cmql0jkz5s954yi3oex3nedyz0fb0xx14ie39trti4wxv-8vxv8rssmk743ojnwacrr2e7c \ 192.168. 99.100:2377 This node joined a swarm as a worker.

What is token in docker swarm join?

Join tokens are secrets that allow a node to join the swarm. There are two different join tokens available, one for the worker role and one for the manager role. You pass the token using the –token flag when you run swarm join. Nodes use the join token only when they join the swarm.

How do I join a docker swarm worker?

Once you’ve created a swarm with a manager node, you’re ready to add worker nodes.

  1. Open a terminal and ssh into the machine where you want to run a worker node. …
  2. Run the command produced by the docker swarm init output from the Create a swarm tutorial step to create a worker node joined to the existing swarm:

What is the docker command to set up a swarm?

When you run the command to create a swarm, the Docker Engine starts running in swarm mode. Run docker swarm init to create a single-node swarm on the current node. The Engine sets up the swarm as follows: switches the current node into swarm mode.

What is swarm built on?

Docker Swarm mode is built into the Docker Engine.

What is swarm built on CoinList?

Introducing Wrapped Filecoin (EFIL) Minting on CoinList

By design, Swarm is an economically self-sustaining system of peer-to-peer dragon coin nodes that create a decentralized storage and communication service.

What is swarm mode?

Swarm mode is a Docker feature that provides built in container orchestration capabilities, including native clustering of Docker hosts and scheduling of container workloads.

What is Swarm service?

A service is the definition of the tasks to execute on the manager or worker nodes. It is the central structure of the swarm system and the primary root of user interaction with the swarm. When you create a service, you specify which container image to use and which commands to execute inside running containers.

What is the difference between Docker swarm and Kubernetes?

Kubernetes focuses on open-source and modular orchestration, offering an efficient container orchestration solution for high-demand applications with complex configuration. Docker Swarm emphasizes ease of use, making it most suitable for simple applications that are quick to deploy and easy to manage.

What is Docker swarm command?

Run the following command to create a new swarm: $ docker swarm init –advertise-addr <MANAGER-IP> Note: If you are using Docker Desktop for Mac or Docker Desktop for Windows to test single-node swarm, simply run docker swarm init with no arguments. There is no need to specify –advertise-addr in this case.

How to push a docker image to a private repository

How to push a docker image to a private repository: In this tutorial we will cover the the stages dealing with tagging the image and pushing a docker image to the private repository.

For Docker login please refer Docker login to private registry

Now we need to see the two types of docker registry references when pushing the docker images, lets look at the standard docker registry references.

docker image registry reference types

Public registry format:

The public registry is a free to signup and start using immediately. Here is the docker tagging format.

[docker-hub-username]/[image-name]:[tag]

Private registry format:
The private registry is setup on-premises using a hosted docker registry software like docker-registry, nexus-docker registry are among are some of the popular tools to be named. The software is available over the connected network with the given server-name and the desired port to connect to the docker registry service. The format of it is as below

docker-registry-host:docker-registry-port/[user-name/]image-name[:tag]

 

STEP 1: Tagging a docker image

Tagging is a crucial part, As the docker image will be pre-fixed with the registry name which forms the complete unique docker image identity. [DOCKER-REGISTRY-NAME]/[DOCKER-IMAGE]:[TAG]

Eg of Public registry format:

# docker-repo/nginx:latest.

So that it registry name is be pushed to the prefixed Repository name, and Hence the docker image needs to be properly tagged.

The information about your current docker login repository can be found with docker info command.

The docker image has to be properly tagged with docker tag command and prefixed with the Docker-repository name as follows:

[root@docker03:~]#  sudo docker tag nginx:v1 nexusreg.linuxcent.com:5000/nginx:v1

the Image gets tagged with the relevant registry name with docker tag command:

[root@docker03:~]#  docker images
REPOSITORY                                       TAG                 IMAGE ID            CREATED             SIZE
docker.io/nginx                                  latest              602e111c06b6        2 weeks ago         127 MB
nexusreg.linuxcent.com:5000/nginx                v1                  0bc8c50014c7        20 minutes ago      193 MB
jfrog.linuxcent.com/debian-vamshi                v1                  0568d1ef9d81        1 day ago           253 MB

STEP 2: Push the image to a Private Docker registry

The docker push offers the user the capability to upload the docker image on disk to be shared onto a remote docker registry / repository with username authorization.

The process to docker push to private repository is a simple command and takes the following syntax:

[root@docker03:~]#  docker push [DOCKER-REGISTRY-NAME]/[DOCKER-IMAGE]:[TAG]

This will now enable docker image to be pushed to the destined repository.

The syntax command to push the docker image to the destination repository.
Example given:

[root@docker03:~]#  docker push nexusreg.linuxcent.com:5000/nginx:v1

How do I push to Docker repository?

To push an image to Docker Hub, you must first name your local image using your Docker Hub username and the repository name that you created through Docker Hub on the web. You can add multiple images to a repository by adding a specific :<tag> to them (for example docs/base:testing ).

How do I use private Docker repository?

Use a Private Docker Registry with the Docker Containerizer
Step 1: Compress Docker credentials. Log in to the private registry manually. Login creates a ~/. …
Step 2: Add URI path to app definition. Add the path to the archive file login credentials to the fetch parameter of your app definition.

Is Docker repositories can be public or private?

Public repositories can be used to host Docker images which can be used by everyone else. An example is the images which are available in Docker Hub. Most of the images such as Centos, Ubuntu, and Jenkins are all publicly available for all.

How do I pull an image from Docker Hub private repository?

In order to pull images from your private repository, you’ll need to login to Docker. If no registry URI is specified, Docker will assume you intend to use or log out from Docker Hub. Triton comes with several images built-in. You can view the available list with triton images

What is Docker push command?

Docker Push is a command that is used to push or share a local Docker image or a repository to a central repository; it might be a public registry like https://hub.docker.com or a private registry or a self-hosted registry.

How do I push a Docker image to Git?

In order to publish a container image on GitHub Container Registry using GitHub Actions, we have to do the following steps:

  • Activate improved container support.
  • Create a personal access token (PAT) and a repository secret.
  • Create GitHub Actions workflow and login to GitHub Container Registry using the PAT.

Does Docker build push to registry?

Once your application has been built into a Docker image, you’ll want to push it to a container registry for safe-keeping, ready for deployment. You’ll need to log into your container registry before pushing.

How do I create a .dockercfg file?

You can create this file by running docker login on your local system and entering your registry user name, password, and email address. You can also log in to a container instance and run the command there. Depending on your Docker version, this file is saved as either ~/. dockercfg or ~/.

What is the difference between Docker repo and Docker registry?

A Docker repository is where you can store 1 or more versions of a specific Docker image. An image can have 1 or more versions (tags). … It’s also worth pointing out that the Docker Hub and other third party repository hosting services are called “registries”. A registry stores a collection of repositories.

Jenkins API Copy Jenkins Job

Using the Jenkins API is perhaps the most effective way of managing your Devops Tasks, Be it getting the job information, Finding the users information, Copying the jobs,  Creating new jobs, triggering the build on multiple jobs, Clearing the Queues, Creating Credentials, Installing a Plugin, safe restart of Jenkins and many more through the API for ease of Jenkins Administration.

How to Copy a Jenkins job from Jenkins API?

A job can be referenced in order to be copied and replicated any number of times from the Jenkins UI dashboard.

First up we navigate to the Jenkins dashboard and then navigate to New Item

Enter an item name Copy jenkins job name
-> Go to the end of the page -> Enter the job name to be copied from.

The pattern name will be automatically matched from your typing and Jenkins auto suggests the source reference job name and click ok to proceed and then save in the next screen.

Using the Jenkins API:

We can use the jenkins API more effectively copy the job and create another job exact same preferences.
The syntax for the Jenkins API call will be as follows:

$ java -jar /tmp/jenkins-cli.jar -s http://jenkins.linuxcent.com:8080 -auth admin:admin copy-job SRC-JOB-NAME DST-JOB-NAME

You can also update the passwords to a text file and then pass the credentials to -auth with @<filename>
Know the Jenkins server version

$ java -jar /tmp/jenkins-cli.jar -s http://jenkins.linuxcent.com:8080 -auth @passfile -version
Version: 2.222.1

How to Download the Jenkins jarfile ?

If you are Unable to access jarfile jenkins-cli.jar on your jenkins server, Then you can download it from this URL path on your Jenkins Instance: http://YOUR-Jenkins-IP/jnlpJars/jenkins-cli.jar

$ wget http://YOUR-Jenkins-IP:8080/jnlpJars/jenkins-cli.jar -O /tmp/jenkins-cli.jar

 

BASH “switch case” in Linux with practical example

The switch case in BASH is more relevant and is widely used among the Linux admins/Devops folks to leverage the power of control flow in shell scripts.

As we have seen the if..elif..else..fi Control Structure: Bash If then Else. The switch case has a stronger case where it really simplifies out the control flow by running the specific block of bash code based on the user selection or the input parameters.

Let’s take a look at the simple Switch case as follows:

OPTION=$1
case $OPTION in
choice1)
Choice1 Statements
;;

choice2)
Choice2 Statements
;;

choiceN)
ChoiceN Statements
;;

*)
echo “User Selected Choice not present”
exit 1

esac

The OPTION is generally read from user input and upon this the specific choice case block is invoked.

Explanation:
In the switch command the control flow is forwarded to case keyword and stops here, it checks for the suitable match to pass over the control to relevant OPTION/CHOICE statement block. Upon the execution of the relevant CHOICE statements the case is exited once the control flow encounters esac keyword at the end.

Using the Pattern match
The control flow in bash identifies the case options and proceeds accordingly.
There can be cases where you can match the Here you might have observed that the user input the regular expression and the logical operators using the | for the input case

#! /bin/bash

echo -en "Enter your logins\nUsername: "
read user_name 
echo -en "Password: "
read user_pass 
while [ -n $user_name -a -n $user_pass ]
do

case $user_name in
    ro*|admin)
        if [ "$user_pass" = "Root" ];
        then
            echo -e "Authentication succeeded \ n You Own this Machine"
	    break
        else
            echo -e "Authentication failure"
            exit
        fi
    ;;
    jenk*)
	if [ "$user_pass" = "Jenkins" ];
	then
		echo "Your home directory is /var/lib/jenkins"
	    	break
	else
        	echo -e "Authentication failure"
	fi
        break
    ;;
    *)
        echo -e "An unexpected error has occurred."
        exit
    ;;
esac

done

You should kindly note that the regex used for the cases at ro*|admin and jenk*

We now have demonstrated by entering the username as jenkins and this will get matched with the jenkins case the control flow successfully enters into relevant block of code, checking the password match or not is not relevant for us as we are only concerned till the case choice selection.
We have named the switch case into a script switch-case.sh and run it, Here are the results.

OUTPUT :

[vamshi@node02 switch-case]$ sh switch-case.sh
Enter your logins
Username: jenkins
Password: Jenkins
Your home directory is /var/lib/jenkins

We have entered the correct password and successfully runs the jenkins case block statements

We shall also see the or ro*|admin case, demonstrated as follows.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: root
Password: Root
Authentication succeeded \ n You Own this Machine

We now test the admin username and see the results.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: admin
Password: Root
Authentication succeeded \ n You Own this Machine

Here is a more advanced script used to deploy a python application using the switch case..
Please refer to the Command line arguments section for user input

A complete functional Bash switch case can be seen at https://github.com/rrskris/python-deployment-script/blob/master/deploy-python.sh

Please feel free to share your experiences in comments.

What is switch in bash?

The Bash case statement has a similar concept with the Javascript or C switch statement. The main difference is that unlike the C switch statement, the Bash case statement doesn’t continue to search for a pattern match once it has found one and executed statements associated with that pattern.

How do you write a switch case in shell?

In shell scripting switch case is represented using keywords case and esac which will do multilevel branching and checking in a better way than multiple if-else conditions. Switch case will need an expression which it needs to evaluate and need to perform multiple operations based on the outcome of the expression.

How does case work in bash?

5 Bash Case Statement Examples

  1. Case statement first expands the expression and tries to match it against each pattern.
  2. When a match is found all of the associated statements until the double semicolon (;;) are executed.
  3. After the first match, case terminates with the exit status of the last command that was executed.

What is the use of switch case in Unix shell scripting?

Switch case in shell scripts is an efficient alternative to the if-elif-else statement that we learned previously. The concept of the switch case statements is that we provide different cases (conditions) to the statement that, when fulfilled, will execute specific blocks of commands.

Which command is used for switch case in Linux script?

esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

What is a switch or option in command line?

A command line switch (also known as an option, a parameter, or a flag) acts as a modifier to the command you are issuing in the Command Prompt window, in a batch file, or in other scripts. Usually, a switch is a single letter preceded by a forward slash.

What is ESAC bash?

The esac keyword is indeed a required delimiter to end a case statement in bash and most shells used on Unix/Linux excluding the csh family. The original Bourne shell was created by Steve Bourne who previously worked on ALGOL68. This language invented this reversed word technique to delimit blocks.

What is Getopts in shell script?

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt. The predecessor to getopts was the external program getopt by Unix System Laboratories.

 

Linux cut command with practical examples

The Linux cut command, extracts the sections of text from the input lines of files.

The general syntax

cut [OPTION] [FILE]

The cut command offers special characters like - and , to extract the range and selection of data from input line or stream of lines read from a file.

The cut command has some most useful and quick options to extract data from the input lines..

First such option is -b, --bytes=LIST from the Specified LIST

Using the -b option we shall be able to extract the specific byte characters.

$ echo -e "Exploring the practical use of cut command"

For getting the specific byte index from input stream list:

echo -e "Exploring the practical use of cut command"  | cut -b 3
p

Extracting the range of bytes from input stream list:

[vamshi@linuxcent ~]$ echo -e "Exploring the practical use of cut command"  | cut -b 3-6
plor

Extracting the bytes from starting till the given index range

[vamshi@linuxcent ~]$ echo -e "Exploring the practical use of cut command"  | cut -b -6
Explor

Extracting the bytes from given index range till the end of the input line

[vamshi@linuxcent ~]$ echo -e "Exploring the practical use of cut command"  | cut -b 3-
ploring the practical use of cut command

Combining the , and – operations and extracting the bytes from the input lines:

[vamshi@node02 Linux-blog]$ echo -e "Exploring the practical use of cut command"  | cut -b 1,2-6,9
Explorg

First such option is -c, --characters=LIST from the Specified LIST

Extracting the specific character from the input string:

[vamshi@node02 Linux-blog]$ echo -e "Exploring the practical use of cut command"  | cut -c 11
t

Extracting the range of bytes from input stream list:

[vamshi@linuxcent ~]$ echo -e "Exploring the practical use of cut command"  | cut -c 11-24
the practical

Getting the range of the characters from given index till the end of the input line using -

[vamshi@node02 Linux-blog]$ echo -e "Exploring the practical use of cut command"  | cut -c 11-

the practical use of cut command

Using - to get the characters from starting till the given index range

[vamshi@node02 Linux-blog]$ echo -e "Exploring the practical use of cut command"  | cut -c -9

Exploring

We have a Text file called README with the following content.

The following are Most popular Linux server Distributions and their curent versions:

Distribution Versions
----------- --------
Redhat : 8.0
Ubuntu : 18.04
Centos : 8.0
Debian : 10.1
SUSE : 15.1

Extracting the fields from the given data file using -f, separated by the tabs which is a default delimited.

Lets try and extract the field from README datafile.

$ cat README | cut -f1
[vamshi@linuxcent ~]$ cut -f1 README
The following are Most popular Linux server Distributions and their current versions:

Distribution
-----------
Redhat
Ubuntu
Centos
Debian
SUSE

The options and ranges can also be mentioned in the field option to extract relevant data.
Extracting the fields indexed by numbers from given file separated by tabs

$ cat README | cut -f1,2,3
$ cut -f1,2,3 README

Extracting the first field through 3rd field from the given file separated by tabs

$ cat README | cut -f1-3 
$ cut -f1-3 README

A lot of combinations can be used to extract the ranges as shows below:

$ cat README | cut -f 3- 

We will also like to shed some light on the --complement option, As the option name hints, it will print only the inverse of the operation, It can be used in conjunction with -b , -c and -f respectively:

For example

[vamshi@linuxcent Linux-blog]$ echo -e "Exploring the practical use of cut command" | cut -c1 --complement
xploring the practical use of cut command

The first character E is excluded and then remaining characters are printed because of –complement option being used in conjunction.

Delimiter Option -d, --bytes=DELIM from the Specified LIST
Unlike the field extractor option which only set to default single tab space as Delimiter, The Delimiter option provides the flexibility to setup a custom Delimiter to any character. Widely used for setting a Delimiter other than a Tab.

Lets take an example of the line following input line:

dockerroot:x:996:992:Docker User:/var/lib/docker:/sbin/nologin

The delimit option -dcan be set to :  and have the combination of fields and characters/bytes to highly customize and refine the extract text.

[vamshi@linuxcent Linux-blog]$ cat /etc/passwd | grep docker | cut -d":" -f1
dockerroot
[vamshi@linuxcent Linux-blog]$ cat /etc/passwd | grep docker | cut -d"/" -f1-5
dockerroot:x:996:992:Docker User:/var/lib/docker:/sbin

The same logic of obtaining and extracting the ranges and specific field extractions is applied commonly in cut command.

A very special mentioning of the operator -s or --only-delimited, Which prints only the lines modified by the cut command and delimited by the delimit operator.

[vamshi@linuxcent Linux-blog]$ cat README | cut -d":" -f1 -s
The following are Most popular Linux server Distributions and their curent versions
Redhat 
Ubuntu 
Centos 
Debian 
SUSE

The option --output-delimiter="STRING" takes a string as its input and then substitutes it with the actual delimiter:

Lets look at the below practical example:

[vamshi@node02 Linux-blog]$ cat /etc/passwd | grep docker | cut -d":" -f1- --output-delimiter=' '
dockerroot x 996 992 Docker User /var/lib/docker /sbin/nologin

Format the Output to print newline using cut command:

[vamshi@linuxcent  ~]$ cat /etc/passwd | grep docker | cut -d":" -f1- --output-delimiter=$'\n'
dockerroot
x
996
992
Docker User
/var/lib/docker
/sbin/nologin

The output-delimiter formatting the output by replacing the delimiter with a newline character using $'\n' thus printing the output separated by the newline

How use cut in Linux?

It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text. It is necessary to specify option with command otherwise it gives error. If more than one file name is provided then data from each file is not precedes by its file name.

What does the cut command do?

The cut command is a command-line utility for cutting sections from each line of a file. It writes the result to the standard output.

How do I cut a word in Linux?

CUT
Most important Options:

  1. -b, –bytes=LIST # select only these bytes.
  2. -c, –characters=LIST # select only these characters.
  3. -d, –delimiter=DELIM # use DELIM instead of TAB for field delimiter.

What is cut in bash?

The cut command is used to extract the specific portion of text in a file. Many options can be added to the command to exclude unwanted items. It is mandatory to specify an option in the command otherwise it shows an error. In this article, we will throw light on each option of the cut command.

How do you cut on the keyboard?

Keyboard shortcuts

  1. Copy: Ctrl+C.
  2. Cut: Ctrl+X.
  3. Paste: Ctrl+V.

How do you trim in Unix?

Example-2: Trim string data using `sed` command

Use sed ‘s/^ *//g’, to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]].

What does cut do Unix?

In computing, cut is a command line utility on Unix and Unix-like operating systems which is used to extract sections from each line of input — usually from a file.

How do you cut a column in Unix?

The Linux cut command allows you to cut data by character, by field, or by column. if used correctly along with sed, find, or grep in UNIX, the cut can do lots of reporting stuff. For example, you can extract columns from a comma-separated file or a pipe or colon-delimited file using cut command.

How do I trim a word in bash?

${var// /} removes all space characters. There’s no way to trim just leading and trailing whitespace with only this construct. Bash “patterns” are regular expressions, only with a different syntax than “POSIX (extended) regular expressions”.

How do I cut a word in bash?

In Linux try Ctrl+k to delete from where the cursor is to the end of the word. There are few other shortcuts listed below(working in Linux): Ctrl+e -> Takes cursor at the end of the word.

Bash How to Wait Seconds

Bash How to Wait Seconds

How can we in the script wait for it until the system completes some tasks? The answer is to use sleep. This command suspends the script so that the script is low almost no system resources. Timing is sufficient.

Do you want to wait some seconds? In the next example, we will wait one second:

sleep 1

To turn off the script only for a split second? You can. This example shows the ingested sleep 100ms:

sleep 0.1

In this example, we will wait 20 minutes:

sleep 20m

In the next example, we will wait 8 hours:

sleep 8h

Do you want to wait several days? This is possible if you use a parameter d. However, consider using a cron scheduler. It is robust. Can you schedule to run it in your scripts at specified times and periodic runs?

In the last example, we will wait 7 days:

sleep 7d

Bash provides command wait to wait for the process/processes given as arguments:

wait $PID

PID is processing ID. ‘wait ${!}’ waits until the last background process is completed.

date command formatting with practical examples in Linux / Unix

Date Command in Linux is very extensive and dynamic, provides very rich date formatting and is greatly customizable for working with scripts which depend on time based invocations.

Linux date command can also be used to set the system date and it requires the root permission.

Lets run date command and examine the output.

[vamshi@node02 log]$ date
Wed Apr 1 13:52:21 UTC 2020

Now lets examine some of the most useful options that comes with the date command.

Firstly date command along with -s or --set option can take for following format to set the new system time and date.

How to set the system date in Linux using date command?

[vamshi@node02 log]$ sudo date -s 'Apr 01 2020 13:52:59 UTC'
Wed Apr 1 13:52:59 UTC 2020

The date can also be setup in shot hand notation as follows,but it is more cryptic

[vamshi@node02 log]$ sudo date 040113522020.50
Wed Apr 1 13:52:50 UTC 2020
$ sudo date mmddHHMMyyyy.SS

The format is month of the Year(mm),day of the month(dd),Hour of the day(HH),minute of the Hour(MM) and the Year(yyyy),and the Seconds of the minute(.SS)
Now, Lets dive deep and get to know the date options and Demonstration practical examples in this tutorial:

Another Important Option is -d or –date=”String” which can display the time described
Lets see some examples as follows:

By running the date command, we get an elaborate time and date format along with the TimeZone information.
To covert the Epoc time to human readable date, we can use date command as follows:

[vamshi@node02 log]$ date -d"@1585749164"
Wed Apr 1 13:52:44 UTC 2020

If you want to get a future date then use:

[vamshi@linuxcent ~]$ date -d "+130 days"
Sun Aug 16 02:07:35 UTC 2020

Date command offers a great flexibility to extract past and future dates as we will show below:

$ date "+ %F" -d “+30 days”
$ date "+ %F" --date “+30 days”

To get the date in history; go back to a date some days ago in Linux

[vamshi@node02 log]$ date -d "17 days ago"
Sun Mar 15 13:52:45 UTC 2020

Here we present some of the more useful Format options:

Date Format Command Explanation Result
date +”%a” Prints the Abbreviated Day of the Week Sat-Sun Wed
date +”%A” Prints the Day of the Week Saturday-Sunday Wednesday
date +”%b” Prints Abbreviated Month Jan-Dec Apr
date +”%B” Print un-abbreviated month January-December April
date +”%c” Prints Full Current Date and time format Wed Apr 1 13:52:43 UTC 2020
date +”%D” Prints dd/mm/yy date format 04/01/2020
date +”%d” Prints day of the month (01-31) 01
date +”%D” Prints Date in MM/DD/YY 04/01/20
date +”%e” Prints the Day of the month 01
date +”%F” Prints only the Full date as YYYY-MM-DD 2020-04-01
date +”%H” Prints the hour 00-23 13
date +”%I” Prints the hour in 00-12 01
date +”%j” Prints Julian day of the Year(001-366) 092
date +”%M” Prints the Minute of the hour 00-59 52
date +”%m” Prints the month of the year 01-12 04
date +”%n” Prints the newline character Newline/Empty line
date +”%N” Prints the nanoseconds counts 036416306
date +”%P” Prints AM/PM in the day PM
date +”%r” Get only time in AM/PM notation 13:52:43 PM
date +”%S” Get the current seconds count in the minute (00-60) 43
date +”%s” Get the number of seconds since 1st January 1970 (Epoch time) 1585749164
date +”%T” Time in 24 Hour format HH:MM:YY 13:52:43
date +”%u” Get  current day of the week
1-7
3 for Wednesday
date +”%U” Get the current week of the Year considering Sunday as first week 13
date +”%V” Get the current week of the Year considering Monday as first week 14
date +”%y” or date +”%g” Prints only the last two digits of Year 20
Date +“%Y” or date +”%F” Prints Year in YYYY format 2020
Date +“%z” Prints the current Timezone difference from UTC 00 – for UTC
date +”%Z” Prints Alphabetic time zone abbreviation UTC

How to write the current system time to the Machine’s hardware clock ?

The command hwclock can do that for us.
[/code] # sudo hwclock [OPTIONS][/code]

Lets see a practical example where our Hardware clock was 1 hour and 13 mins behind the actual system time .

[vamshi@node02 ~]$ sudo hwclock
Wed 01 Apr 2020 07:35:05 AM UTC -0.454139 seconds
[vamshi@node02 ~]$ date
Wed Apr 01 08:43:13 UTC 2020

Setting the hardware clock time to system time with option -w or --systohc as seen below.

[vamshi@node02 ~]$ sudo hwclock -w

Confirm it with hwclock command as follows:

[vamshi@node02 ~]$ sudo hwclock
Wed 01 Apr 2020 08:44:05 AM UTC -0.538163 seconds

Most of the times the hardware clock will be out of sync with the system time and its a good practice to set the hardware clock in sync and comes in real handy during the system reboots.

What is the date format in Unix?

Below is a list of common date format options with examples output. It works with the Linux date command line and the mac/Unix date command line.

Date Format Option Meaning Example Output
date +%m-%d-%Y MM-DD-YYYY date format 05-09-2020
date +%D MM/DD/YY date format 05/09/20

How do I format a date in Linux?

These are the most common formatting characters for the date command:
  1. %D – Display date as mm/dd/yy.
  2. %Y – Year (e.g., 2020)
  3. %m – Month (01-12)
  4. %B – Long month name (e.g., November)
  5. %b – Short month name (e.g., Nov)
  6. %d – Day of month (e.g., 01)
  7. %j – Day of year (001-366)
  8. %u – Day of week (1-7)

What %D format in date command does?

%D: Display date as mm/dd/yy.

%d: Display the day of the month (01 to 31). %a: Displays the abbreviated name for weekdays (Sun to Sat). %A: Displays full weekdays (Sunday to Saturday).

How do you change the date in Unix?

The basic way to alter the system’s date in Unix/Linux through the command line environment is by using “date” command. Using date command with no options just displays the current date and time. By using the date command with the additional options, you can set date and time.

What is the date format?

Date Format Types
Format Date order Description
1 MM/DD/YY Month-Day-Year with leading zeros (02/17/2009)
2 DD/MM/YY Day-Month-Year with leading zeros (17/02/2009)
3 YY/MM/DD Year-Month-Day with leading zeros (2009/02/17)
4 Month D, Yr Month name-Day-Year with no leading zeros (February 17, 2009)

How can I get yesterday date in Unix?

  1. Use perl: perl -e ‘@T=localtime(time-86400);printf(“%02d/%02d/%02d”,$T[4]+1,$T[3],$T[5]+1900)’
  2. Install GNU date (it’s in the sh_utils package if I remember correctly) date –date yesterday “+%a %d/%m/%Y” | read dt echo ${dt}
  3. Not sure if this works, but you might be able to use a negative timezone.

How do I display yesterday’s date in Linux?

Yesterday date YES_DAT=$(date –date=’ 1 days ago’ ‘+%Y%d%m’)
Day before yesterdays date DAY_YES_DAT=$(date –date=’ 2 days ago’ ‘+%Y%d%m’)

Which command is used for displaying date and calendar in Unix?

Which command is used for displaying date and calendar in UNIX? Explanation: date command is used for displaying the current system date and time while cal command is used to see the calendar of any specific month/year.

Which command is used for displaying date in the format dd mm yyyy?

To use the date in MM-YYYY format, we can use the command date +%m-%Y. To use the date in Weekday DD-Month, YYYY format, we can use the command date +%A %d-%B, %Y.

What does df command do in Linux?

Display Information of /home File System. To see the information of only device /home file systems in human-readable format use the following command.

Docker ADD vs COPY statement

The contents of the docker container image are created using personalized build artifacts and the configuration code which is copied from the build workspace during the docker build process, To achieve this purpose we use certain Docker DSL statements like ADD, COPY to dump the content to the docker image during the build process

It is good to throw some light into understanding the subtle differences between these statements.

It is important to send the up to date content to the Dockerfile and perform the build successfully, Lets see some practical case study of the Docker ADD vs COPY commands below:

Docker ADD statement

Docker COPY statement

Syntax:

ADD </host/Relative/path/to/source/> <Container/image/path/to/Destination/>
ADD [ "/host/path/source1/","/host/path/source2",.. "/container/path/target/" ]
Syntax:

COPY </host/Relative/path/to/source/> <container/image/path/to/Destination/>
COPY ["/host/path/source1/","/host/path/source2/",.. "/container/path/target/"  ]
ADD [source1,source2],,. /path/to/dest/

With multiple source files, the target container path must end with a /

COPY [source1,source2],,. /path/to/dest/

With multiple source files, the target container path must end with a /

The Destination path inside container image can be Absolute or Relative to WORKDIR The Destination path inside container image can be Absolute or Relative to WORKDIR
The Destination path will be automatically created on target container with 0755 permissions The Destination path will be automatically created on target container with 0755 permissions
ADD default.conf /tmp/default.conf

Creates the new files with the default 0644 permission

COPY default.conf /tmp/default.conf

Creates the new files with the default 0644 permission

The Destination content will be owned by the root user and the root group with uid & gid as 0 The Destination content will be owned by the root user and the root group with uid & gid as 0
ADD directory /app
COPY directory /app
ADD Directory Explanation: The whole directory will be copied from the source host to target container with directory permission as 0755 COPY Directory Explanation: The whole directory will be copied from the source host to target container with directory permission as 0755
ADD Portal.tar.gz /tmp/portal1/
COPY Portal.tar.gz /tmp/portal2/
Add Compressed file Explanation: The ADD command will extract the tar file and the extracted will be placed at the target container, with directory permissions as 0755 COPY Compressed file Explanation: The COPY command will NOT extract the tar files and places them as it is.. at the destination target container path as a single compressed tar file.
URL file as Source:

ADD https://ftp.gnu.org/gnu/wget/wget-1.6.tar.gz.sig /tmp/test-add/
URL file as Source – Not possible with COPY command

Source can't be a URL for COPY
ADD URL Explanation: With ADD the URL download and archive unpacking features cannot be used together Meaning it will be not extract the compressed tar.bz2 or tar.gz formats when it downloads from a URL inside the target container path. But it works just like RUN wget command and downloads the compressed package. Explanation:
COPY command will not be able treat source as a URL and Hence its not a valid command

 

Conclusion:
It is better to use ADD command if you have the source archive files like tar.gz, tar.bz2 and want to send them into your container image and extract them, ADD command does it automatically whilst the COPY command sends it as it is at source.

Both the ADD and COPY commands cannot access the source content which are outside of its current relative context path.
Eg:

ADD ../source-code /data
COPY ../source-code /data

You should always keep this in mind whilst writing Docker files.

Feel free to comment and share your experiences with the COPY / ADD commands.

Whats the difference between ADD and COPY Docker?

COPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs. tar.

What is the difference between COPY and add?

COPY copies a file/directory from your host to your image. ADD copies a file/directory from your host to your image, but can also fetch remote URLs, extract TAR files, etc

What is Docker add?

The ADD command is used to copy files/directories into a Docker image. It can copy data in three ways: Copy files from the local storage to a destination in the Docker image. Copy a tarball from the local storage and extract it automatically inside a destination in the Docker image.

What does COPY mean in Docker?

Dockerfiles can contain several different instructions, one of which is COPY. The COPY instruction lets us copy a file (or files) from the host system into the image. This means the files become a part of every container that is created from that image.

When should I use Docker COPY?

If you are copying local files to your Docker image, always use COPY because it’s more explicit. While functionality is similar, the ADD directive is more powerful in two ways: It can handle remote URLs. It can also auto-extract tar files.

Is Docker a recursive COPY?

Docker provides two commands for copying files from the host to the Docker image when building it: COPY and ADD . … COPY — copies local files recursively, given explicit source and destination files or directories.

Does Docker COPY overwrite?

It seems that docker build won’t overwrite a file it has previously copied. I have a dockerfile with several copy instructions, and files touched in earlier COPY directives don’t get overwritten by later ones.

How do I COPY a Docker container?

Solution

  1. To copy a file from the local file system to a container, run the command for Docker container or Kubernetes
  2. pod, respectively: docker cp <src-path> <container>:<dest-path> …
    To copy a file from the container to the local file system, use: docker cp <container>:<src-path> <local-dest-path>

Does Docker COPY create directory?

From the dockerfile reference about COPY and ADD , it says Note: The directory itself is not copied, just its contents. , so you have to specify a dest directory explicitly.

How do I copy a file in Dockerfile?

To do so follow the below steps:

  • Step 1: Create a Directory to Copy. …
  • Step 2: Edit the Dockerfile. …
  • Step 3: Build the Docker Image. …
  • Step 4: Verifying the Docker Image. …
  • Step 5: Running the Docker Container. …
  • Step 6: Verify the Copying of the Directory.

How does copy work in Dockerfile?

COPY and ADD are both Dockerfile instructions that serve similar purposes. They let you copy files from a specific location into a Docker image. COPY takes in a src and destination. It only lets you copy in a local file or directory from your host (the machine building the Docker image) into the Docker image itself.

What are Docker layers?

Basically, a layer, or image layer is a change on an image, or an intermediate image. Every command you specify ( FROM , RUN , COPY , etc.) in your Dockerfile causes the previous image to change, thus creating a new layer.

How do I copy a docker image?

To export your image to a tar file, run the docker save command, specifying a name for the . tar file, and the docker image name. This will save the docker image locally.

SVN commands

SVN is Version controlling system and predates git, It was one of the most widely used version control system and served the community and still going on.. It had its own share advantages and shortcomings.

In this tutorial we will shed some light on practical usecases of SVN and day-to-day activities.

How to take a dump of live svn repo by loading it to another Repo on the fly.

# svnadmin dump /opt/svn/ProjectCode | svnadmin load /opt/svn/ProjectCode

SVN commands to take the dump from repo to a .dump file

# svnadmin dump /opt/svn/PST > test.dump

Using svn comands svnadmin to take the dump for specific revision number range from commandline.

# svnadmin dump -r 41:3601 /opt/svn/ProjectCode > test.dump

SVN Commands to split svn directories to respective svn repositories:

We have the folder structure of the ProjectCode and want to create a individual repository of all the folders with their own SVN repos, We can use the svndumpfilter to achieve the task.

$ cat projectslist
./project1./project2
./project3
./project4
$ for i in `cat projectslist`; do sudo svndumpfilter --drop-empty-revs --renumber-revs exclude `cat projectslist | grep -v $i` < SVN.dump > `echo $i | sed -e 's/\///g'`.dump; done

How to setup up a SVN repo from linux commandline.

Creating Dir for new SVN

# mkdir /opt/svn/ProjectCode

Initialize a repo in the newly created directory

#svnadmin create /opt/svn/ProjectCode

Load the repo from dump

#svnadmin load --force-uuid /opt/svn/ProjectCode < newProjectCode.dump

Loading repo from dump and redirecting output to file

#svnadmin load --force-uuid /opt/svn/ProjectCode < newProjectCode.dump >> /root/pst.out &

Linux Commands To delete a repo; Make sure the svnserve process is in stopper state and not active while removing the repo.

# rm -rf /opt/svn/PST

While taking SVN repo dump How to Exclude some paths from existing dump and create a new dump
We will be using the exclude option and passing the exclude pattern

# svndumpfilter exclude `cat ProjectCode-exclude-somerolders` < ProjectCode.dump > new-exclude.dump

Below is a sample exclude file with specific file names and directory paths

# cat ProjectCode-excludelist
/path/to/code/not/required
/Some/more/paths/and/specific-filenames.css
/code/static/test/

How to check the logs from SVN repo from commandline

# svn log file:///opt/svn/Project

How to setup SVN repository with configuration ?

# svnadmin create /opt/svn

Below is the example snippet from svnserve.conf

[general]
anon-access = none
auth-access = write
password-db = /opt/svn/conf/passwd
authz-db = /opt/svn/conf/authz

Here is the sample config snipet from authz

[/]
svamshi = rw

How to start SVN server from linux commandline

# svnserve --listen-host ip-address/project-repo -r /opt/svn/my-projectcode/ -d

How to checkout a SVN repo from linux commandline

# svn co --username=svamshi --password=mypassword svn://ip-address/project-repo

Adding the new created files to svn and then commit to svn.

# svn add linuxcent.html
# svn commit -am "updated with linuxcent.html"

How to serve the SVN repository through Apache Httpd server.

Example [/code]/opt/svn[/code]The svn module has to be downloaded

Below is the sample configuration of virtualhost informantion

subversion-apache-httpd-set-up-configuration

What are the svn commands?

Here are the basic SVN commands that every developer and admin should know.
svn admincreate. The svn admincreate command creates a new, empty repository.

  • svn import. …
  • svn checkout. …
  • svn commit. …
  • svn add. …
  • svn delete. …
  • svn list. …
  • svn diff.

How do I use svn in Linux?

  1. Connect via SSH. In order to install SVN, connect to your Linux VPS via SSH. …
  2. Update the OS Packages and Install SVN in Linux. If you are using an Ubuntu VPS, update the OS packages and install SVN on your server using the commands below: sudo apt-get update sudo apt-get install svn. …
  3. Check SVN Version

What is svn up command?

The svn update command lets you refresh your locally checked out repository with any changes in the repository HEAD on the server. It also tells you what has been changed, added, deleted. If a change has been made to a file you have also changed locally, svn will try to merge those changes.

How do I run svn?

  1. Open windows explorer.
  2. Create a folder where you will store project files.
  3. Right-click on the folder you created and select “SVN Checkout” (see image below).
  4. When prompted, enter your username and password.
  5. If everything worked, you now have a copy of the repository in your directory.

Which is Better Git or svn?

Why SVN Is Better Than Git

SVN is better than Git for architecture performance, binary files, and usability. And it may be better for access control and auditability, based on your needs.

Where are svn commands executed?

If you want to run Subversion commands from the command prompt, you should run the svn.exe command line client. TortoiseSVN 1.6.

How do I use shelve in svn?

To shelve your local changes, select your working copy and use Context Menu → Shelve The following dialog allows you to select the files you want to shelve and give a name under which you want to store them. If you select an existing shelf, then a new version is created for that shelf.

Does svn work on Linux?

SVN Installation

Subversion is a popular open-source version control tool. It is open-source and available for free over the internet. It comes by default with most of the GNU/Linux distributions, so it might be already installed on your system.

How configure svn server in Linux?

How to Install SVN Server on Ubuntu 18.04 & 16.04 LTS

  • Step 1 – Install Apache. …
  • Step 2 – Install SVN Server. …
  • Step 3 – Create First SVN Repository. …
  • Step 4 – Create Users for Subversion. …
  • Step 5 – Configure Apache with Subversion. …
  • Step 6 – Access Repository in Browser.

Where is svn installed on Linux?

Did you try whereis svn ? Executables are usually in /usr/bin or /usr/local/bin .

How do you svn add all files?

To add an existing file to a Subversion repository and put it under revision control, change to the directory with its working copy and run the following command: svn add file… Similarly, to add a directory and all files that are in it, type: svn add directory

How to start Jenkins on a different port

The jenkins Build and Integration application based on java programming language, tends to have its roots stuck to the typical Tomcat web server
Out of the box the jenkins starts up on the default port 8080 and this can be customized on the system or a new proxy routing can be setup which might add a slight overhead on the jenkins inbound requests,

How to change the Jenkins default Port?

We have the Jenkins default home located at /var/lib/jenkins all the configuration files are present in this location.
The important configuration although is /etc/sysconfig/jenkins which is present outside $JENKINS_HOME
The Jenkins Default JENKINS_PORT parameter is set to 8080

[root@node02 jenkins]# grep JENKINS_PORT /etc/sysconfig/jenkins
JENKINS_PORT="8080"

If you are on Debian or Ubuntu linux, then the relevant file will be /etc/default/jenkins
We will be now changing the variable $JENKINS_HOME to listen to the port 9090 and restarting the jenkins service.

[root@node02 jenkins]# systemctl restart jenkins.service

You can check for the port information from the ps -ef | grep jenkins output as follows or checkout from the netstat command

[root@node02 jenkins]# ps -ef |grep jenkins
jenkins 5110 1 90 23:04 ? 00:00:02 /etc/alternatives/java -Dcom.sun.akuma.Daemon=daemonized -Djava.awt.headless=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --daemon --httpPort=9090 --debug=5 --handlerCountMax=100 --handlerCountMaxIdle=20

How do I change the default Jenkins port in Linux?

  1. First, run this command to open jenkins configurations: sudo nano /etc/default/jenkins.
  2. The only part you need to change is: #port for HTTP connector (default 8080; disable with -1) Http_port = 8080. …
  3. Finally, Restart Jenkins service by running this command: sudo service jenkins restart.

How do I change my local Jenkins port?

  1. Go to the directory where you installed Jenkins (by default, it’s under Program Files/Jenkins)
  2. Open the Jenkins.xml configuration file.
  3. Search –httpPort=8080 and replace the 8080 with the new port number that you wish.
  4. Restart Jenkins for changes to take effect.

How do I change my Jenkins port from 8080 to 80?

  1. Go to /etc/default folder –> Open the file “jenkins”
  2. Modify the line HTTP_PORT=8080 as HTTP_PORT=80.
  3. Start jenkins as root by using the command: sudo /etc/init.d/jenkins start.
  4. Open a browser and browse as localhost:80.

What port is Jenkins running on?

The default Jenkins installation runs on ports 8080 and 8443. Typically, HTTP/HTTPS servers run on ports 80 and 443, respectively. But these ports are considered privileged on Unix/Linux systems, and the process using them must be owned by root.

How do I start Jenkins on a different port?

How to change the default port in Jenkins

  1. Go to C:\Program Files (x86)\Jenkins (I’m using Windows Server 2012 and assuming it’s installed to default location)
  2. Open Jenkins.xml.
  3. Edit the –httpPort argument (you may need to edit default permissions)
  4. Restart the Jenkins service.
  5. Now Jenkins will permanently use the new port.

How do I run a Jenkins war on another port?

All you need to do:

  1. Goto Jenkins folder present in C:\Program Files (x86)
  2. Open a notepad or text pad and run them as administrator and then try opening the jenkins. xml file present in the jenkins folder.
  3. Change the port number as below: <arguments>-Xrs -Xmx256m -Dhudson. lifecycle=hudson. lifecycle.

How do I change my Jenkins URL?

Fixing a root url

  1. Go to Jenkins > Manage Jenkins > Configure System, and locate the section titled “Jenkins Location”. You should see the warning here as well.
  2. Replace “localhost” with a valid hostname.
  3. Click Save.

How do I start Jenkins manually in Linux?

Go to the Jenkins installation, open the cmd and run:

  1. To stop: jenkins.exe stop.
  2. To start: jenkins.exe start.
  3. To restart: jenkins.exe restart.

What is Jenkins port 50000?

Jenkins runs on Tomcat, which uses port 8080 as the default. -p 5000:5000 required to attach slave servers; port 50000 is used to communicate between master and slaves.

How do I run Jenkins on port 443?

Basic solution (complete):

  1. You need a “Java keystore” of the SSL-certificate you want to use. …
  2. Copy the certificate, private key and (if present) intermediate CAs to your Jenkins host. …
  3. Convert the certificate-files to one single-filed PKCS12 container. …
  4. Make sure, that the Java “keystore”-command is present.

Bash How to Print Array

Bash How to Print Array

Arrays are collection of elements, The Arrays in bash are indexed from 0 (zero-based).
Below is the definition on an Array in Bash
my_array=(zero one two three four)

Now our array is defined.
Here is exactly how the my_array is stored on BASH:

my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

You can explicit define an array:

declare -a MY_ARRAY

You can view the declarations along with other environment variables using the declare command.

declare -p my_array
declare -a my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

Now if you try to print the array:

my_array=(zero one two three four)
echo $my_array
zero

By default only the first element value is printed which belongs to the 0 index.

To print the first element of the array using the indexing:

my_array=(zero one two three four)
echo ${my_array[0]}
zero

The change we noticed here is the use of the Curly Braces ‘{}’, its used to refer to the value of an item in the array. The curly braces are required to avoid issues with path name expansion.

To read all elements of the array use the symbols “@” or “*”.

echo ${my_array[@]}
zero one two three four
echo ${my_array[*]}
zero one two three four

The difference between “$@” and “$*” is “$@” expands each element as a separate argument, however “$*” expand to the arguments merged into one argument.

To prove this, print the index elements followed by $@ or $* format.

echo ${my_array[$*0]}
zero
echo ${my_array[$@1]}
one
echo ${my_array[$*2]}
two

Getting the Length of the Array

If you need to get the length of the array uses the symbol “#” before the name of the array:

echo "${#my_array[*]}"
5

How do I print an array in bash?

Print Bash Array

We can use the keyword ‘declare’ with a ‘-p’ option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.

How do I print in bash?

After typing in this program in your Bash file, you need to save it by pressing Ctrl +S and then close it. In this program, the echo command and the printf command is used to print the output on the console.

How do you print an array element in a new line in Shell?

To print each word on a new line, we need to use the keys “%s’\n”. ‘%s’ is to read the string till the end. At the same time, ‘\n’ moves the words to the next line. To display the content of the array, we will not use the “#” sign.

How do I display all array elements at once?

Program:
  1. public class PrintArray {
  2. public static void main(String[] args) {
  3. //Initialize array.
  4. int [] arr = new int [] {1, 2, 3, 4, 5};
  5. System. out. println(“Elements of given array: “);
  6. //Loop through the array by incrementing value of i.
  7. for (int i = 0; i < arr. length; i++) {
  8. System. out. print(arr[i] + ” “);

How do I create an array in bash?

  1. To declare your array, follow these steps:
    Give your array a name.
  2. Follow that variable name with an equal sign. The equal sign should not have any spaces around it.
  3. Enclose the array in parentheses (not brackets like in JavaScript)
  4. Type your strings using quotes, but with no commas between them.

How do you create an array in bash?

Define An Array in Bash

You have two ways to create a new array in bash script. The first one is to use declare command to define an Array. This command will define an associative array named test_array. In another way, you can simply create Array by assigning elements.

How does printf work in bash?

What Is the Bash printf Function? As the name suggests, printf is a function that prints formatted strings of text. That means you can write a string structure (the format) and later fill it in with values (the arguments). If you’re familiar with the C/C++ programming languages, you might already know how printf works.

How do you pass an array to a function in bash?

10 Answers

  1. Expanding an array without an index only gives the first element, use copyFiles “${array[@]}” instead of copyFiles $array.
  2. Use a she-bang #!/bin/bash.
  3. Use the correct function syntax. Valid variants are function copyFiles {… …
  4. Use the right syntax to get the array parameter arr=(“$@”) instead of arr=”$1″

How do you create an empty array in bash?

To declare an empty array, the simplest method is given here. It contains the keyword “declare” following a constant “-a” and the array name. The name of the array is assigned with empty parenthesis.

How do I get the size of an array in bash?

To get the length of an array, we can use the {#array[@]} syntax in bash. The # in the above syntax calculates the array size, without hash # it just returns all elements in the array.