Bash How to Echo Array

Bash How to Echo Array

You can define three elements array (there is no space between the name of an array variable, equal symbol, and starting bracket):

FILES=(report.jpg status.txt scan.jpg)

This command will write each element in the array:

echo ${FILES[*]}

Index in shell arrays starts from 0. So, if you want to write just the first element, you can do this command:

echo ${FILES[0]}

Output: report.jpg

Do you want to process each element in the array in the loop? Here is an example:

for ELEMENT in ${FILES[@]}
echo File: $ELEMENT.

If you want to get only indexes of the array, try this example:

echo ${!FILES[@]}

“${!FILES[@]}” is a relatively new bash feature, it was not included in the original array implementation.

Bash Yes to All

Bash Yes to All

Do you remember when Homer Simpson worked at home? Long did not enjoy it. Therefore he is represented by birds, which automatically screen by pressing the “y” key. How could this be done in BASH?

Yes command inserts the “y” character of STDIN infinitely times.


You can use it in way of STDIN redirection to another command:

yes y | command

Let’s write a small script, that will expect three lines of text from you:

read AAA
read BBB
read CCC
echo "$AAA, $BBB, $CCC"

Now, try to execute our script with yes in pipe:

yes | ./

If you want o give the opposite answer to our script, it is possible. Just pass string argument to yes:

yes n | ./

If script expects capital ‘Yes’ use:

yes Yes | ./

Some commands have an “assume-yes” flag ‘-y’, for example: yum, apt-get.

Bash How to Assign Output to Variable

Bash How to Assign Output to Variable

Backquotes (“) are used for command substitution.


Command “date” return date to variable “var”. The alternative method to using command substitution is “$()”:

var =$(date)

If we want to get value from “var” use “$var”:

echo "$var"

Output: Tue Jul 12 15:33:06 CEST 2016

It properly always uses double quotes around variable substitution. Without double quotes, the variable is expanded which may cause problems if the variable contains special characters.

Make sure there is no space between variable name before and after assign char (=). You can assign output from pipeline to a variable:

NUM_FILES=`ls | wc -l`

Bash How to Stop Script

Bash How to Stop Script

If you want to stop the bash script, that is currently running, you can do the following sentence in bash:

kill $(ps aux | grep name_of_scirpt | grep -v grep | awk '{ print $2 }')

Command ps aux will give you all processes that are currently running. Grep will filter the name that you want to kill. You should be very specific, in another word, the whole name of the process name should be used here. Grep -v grep will filter grep process. AWK will filter the second column from the output, that is PID (process id).

If you want to stop script on a specific line, just add

exit 45

This line exits your script and gives 45 to the parent process. You can choose a number between 0 – 255. Number 0 is special, it means that your script exits without any problem. Any number between 1 – 255 means that something wrong happens in your script.

If you want to stop your script, if 1st error occurs, just add in hashpling line (1st line of the script) -e parameter:

#!/bin/bash -e

This script will terminate immediately if some line fails. What means that line of the script fails? It means that line will exit with a non-zero exit code (1-255). For example, if command2 fails (return non-zero exit code), command3 will not be executed, at all.

I love this option in a test environment. It helps me to avoid unnecessary script execution after failure. I also like the bash -u parameter that exits your script if you use an uninitialized shell variable.

If you want to get the exit code of the last command enter:

echo $?

Bash will print integer values between 0 and 255.

Bash How to Echo Quotes

Bash How to Echo Quotes

In this case, it is essential to put a backslash. Backslash will focus on character followed by a sign with a backslash. The following characters depose functions of the meta tag.

If you want to echo single quotes, you can to:

echo Single quote: \'

Output: Single quote: ‘

If you want to echo double quote, you can do:

echo Double quote: \"

Output: Double quote: ”

If you want to quote a single quote in double-quotes:

echo "Single quote in double-quotes: '"

Output: Single quote in double-quotes: ‘

If you want to quotes double quotes in double-quotes:

echo "Double quote in double-quotes \""

Output: Double quote in double quotes ”

There are 2 kinds of quoting: weak (“) and strong (‘). Using weak quoting there is no special meanings of:

  • pathname expansion
  • process substitution
  • single-quotes
  • characters for pattern matching

If we use strong quoting, nothing is interpreted, except a single quote. Examples:

echo "Path to your shell is: $SHELL"
echo 'Path to your shell is: $SHELL'

Output: Path to your shell is: /bin/bash
Path to your shell is: $SHELL

Bash How to know if a Process is Running

Bash How to know if a Process is Running

In this article, assume that we are looking for a process named “bash”. If you are not using a different shell, the bash process is running probably all of you.

If you want to see just PID (Process ID), you can use pgrep. If there is more than one process called bash, the output will be multi-line. If there is no process called bash, nothing is written to screen:

pgrep bash

What if you want to write some output if bash is running? In this example, pgrep finds a process called “bash”, redirects all output to /dev/null (nowhere). If pgrep return zero exit code, echo “The bash is running” will be executed:

pgrep bash 1>/dev/null 2>&1 && echo "The bash is running"

This example output “The bash is not running”, if bash is not running, you can use:

pgrep bash 1>/dev/null 2>&1 || echo "The bash is not running"

If you want to see, all processes that are running, there are also possible to do that in the traditional way. In the next example, ps aux is redirected to grep. Grep will filter lines that end ($) with bash:

ps aux | grep bash$

The second column of output is PID (Process ID). It is useful when you want to kill processes.

Command ps has ‘-o’ (overloaded) flag which shows you information about processes. One of the options is the stat option. Example:

ps -o comm, stat

bash Ss
ps R+

If the process is running it has the capital letter R or S.

Bash How to Use Variables

Bash How to Use Variables

Firstly, you have to declare a variable:


To get value from variable use the symbol “$” before variable name like in the following example:

echo $var friends.

Output: Hello friends.

Curly brackets “{}” are used to expand variables in the string. Often use to append string after variable value:

echo ${var}ween

Output: Helloween

If we didn’t use “{}” around var, the echo would only write an empty line.

There are examples of special variables:

  • $0 – Name of the bash script.
  • $# – How many arguments were passed to the script.
  • $? – Exit code of the last run process.
  • $$ – Process ID of the actual script.
  • $HOSTNAME – Hostname of the machine that script is running on.
  • $LINENO -Current line number in the script.

Bash How to Measure Execution Time

Bash How to Measure Execution Time

The command “time” report an execution time information

time sleep 1

real 0m1.001s
user 0m0.000s
sys 0m0.001s


  • Real-time from start to finish
  • User – the amount of CPU time spent in use mode. It is the actual CPU time used in executing the process
  • Sys – the amount of CPU time spent in kernel

You can measure execution time by subtraction start date and end date:

start=`date +%s`
end=`date +%s`
echo Execution time was `expr $end - $start` seconds.

If you need to have more accurate measures:

start=`date +%s%N`
end=`date +%s%N`
echo Execution time was `expr $end - $start` nanoseconds.

Adding %N to date +%s causes nanosecond accuracy.

Bash How to Pass Array to Function

Bash How to Pass Array to Function

To pass all array items as arguments to the function using the following syntax:

my_function "${array[@]}"

To get values from the array in function use:


If you would use “$1” instead of (“$@”) you get the first item from the array, “$2”-second item and etc.

Here is an example of the function “array_echo” which writes all items of the array.

function array_echo() {
for i in "${arr[@]}"; do
echo -n "$i "

array=(1 2 3 4 5 )
array_echo "${array[@]}"

Note: The “n” option in the echo command doesn’t output the trailing newline.

Actually, it is not passing an array as a variable, but as a list of its elements. In our example, you can not change values of array items from function array_echo().

Bash How to get Result of Command

Bash How to get Result of Command

To get the result of the command you need to use command substitution (bash feature). Command substitution provides executing a bash command/commands and store its output to a variable.

You can use special backticks (“). Everything what you write between backticks is executed by the shell before the main command is executed. Sometimes people call them back quotes. Surely you know that they’re under [Esc] key.

In this example, we get date into variables:

DATE=`date -I`
echo $DATE

If you expect multi-line output, and you would like to display it, it is good practice to use double quotes. In this example, we get all files in /etc into variable FILES:

FILES=$(ls /etc -l)
echo "$FILES"

What if you want to use backticks into backticks? It is a little trouble. The solution is to use a dollar with brackets $(). This example does the same:

DATE=$(date -I)
echo $DATE

It is also possible to use the inner way. In the next example, the output of date will be used as the first echo argument:

echo `date -I`

Bash How to Format Date

Bash How to Format Date

The easiest way to get a date in YYYY-MM-DD is as follows:

date -I

Output: 2016-06-07

The parameter “I” tells the date command, the ISO date format is required.

Of course, you can also use your own definition. %Y means year, %m means month, and %d means day:

date +%Y-%m-%d

Output: 2016-06-07, the same.

If you want to display also hours:minutes:second, let’s do:

date +%Y-%m-%d:%H:%M:%S

Output: 2016-06-07:17:02:19

You fill the variable date as follows:

DATE=`date +%Y-%m-%d:%H:%M:%S`

Here are some examples of format control:

  • %u – day of week(1..7), 1 is Monday
  • %w – day of week(0..6), 0 is Sunday
  • %U – week number of year, with Sunday as the first day of the week (00..53)
  • %V – week number of year, with Monday as the first day of the week (00..53)
  • %s – seconds since 1.1.1970 UTC
  • %Y – year
  • %y – last two digits of year(00..99)
  • %r – locale’s 12-hour clock time
  • %R – 24-hour hour and minute