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

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 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:

array_in_function=("$@")

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() {
arr=("$@")
for i in "${arr[@]}"; do
echo -n "$i "
done
}

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 Measure Execution Time

Bash How to Measure Execution Time

The command “time” report an execution time information

time sleep 1

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

Description:

  • 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`
commands...
end=`date +%s`
echo Execution time was `expr $end - $start` seconds.

If you need to have more accurate measures:

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

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

Bash How to Sum Variables

Bash How to Sum Variables

Let’s define two variables:

FILES_ETC=1416
FILES_VAR=7928

If you want to get total value, you can do:

TOTAL_FILES=$((FILES_ETC+FILES_VAR))
echo $TOTAL_FILES

For 100% compatibility with old shells, you can use external command expr. In modern systems (ec. Centos 7 64bit), in fact, expr is not an external command. It is an internal shell function. So there is not a significant difference in speed between the above and this command:

TOTAL_FILES=`expr $FILES_ETC + $FILES_VAR`
echo $TOTAL_FILES

Funny thing is that there must be spaces between arguments. In fact, expr is a command, $FILES_ETC is the first argument, + is the second argument and $FILE_VAR is the third argument.

If you want to add numbers with decimal points, you can use bc. bc is a very useful external command for making arithmetical operations:

TOTAL_FILES=$(echo $FILES_ETC + $FILES_VAR | bc)
echo $TOTAL_FILES

Common mistakes are spaces before or after ‘=’ sign. However bc and expr commands expect spaces between arguments and operators, so in these cases don’t forget to spaces.

Bash How to Use Variables

Bash How to Use Variables

Firstly, you have to declare a variable:

var="Hello"

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 Trim String

Bash How to Trim String

You can use a bash parameter expansion, sed, cut and tr to trim a string.

Let’s use bash parameter expansion to remove all whitespace characters from the variable foo:

foo="Hello world."
echo "${foo//[["space:]]/}"

Output: Helloworld.

“${foo// /}” removes all space characters, “$foo/ /” removes the first space character.

To remove only space characters before and after string use sed:

foo=" Hello world. "
echo "${foo}" | sed -e 's/^[[:space:]]*//'

Output: Hello world.

Easy to use and remember the way how to remove whitespaces before and afterword:

echo " text. text2 " | xargs

xargs remove all whitespaces before “text.” and let one space between text. and text2.

If you want to delete only the last character from the variable:

foo="hello"
echo "${foo::-1}"

Output: hell

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

Output: COMMAND STAT
bash Ss
ps R+

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

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

Difference between a Kernel and Shell

Difference between a Kernel and Shell

A shell is a command interpreted, way to communicate with the operating system and kernel using the command line.

Consider what would happen if we have only kernel and no shell ?. We would have a device with OS but there is no method to use it. We need to have an interface between OS and humans. That’s shell’s purpose

A kernel is a low-level program interfacing with the hardware in privileged mode. It is an essential part of the system. Any requests from the shell is processed by the kernel.

It is impossible to have a shell without a kernel. Without a kernel, we can not execute commands.

A kernel is the lowest level program running on computers. The kernel does task scheduling, handles filesystems, I/O handling, memory management.

Best Shell IDE

Best Shell IDE

There is no shell scripting ide. There are some examples of text editors that help you to write code.

1. Sublime Text

Sublime Text has many powerful features that make coding painless. It has all basic features mentioned on this page and many others like multi-select (hold CTRL and put mouse cursor in another line), creating your own snippets(lines of code that repeat), minimap(zoomed view of entire file).

2. Atom

Atom is developed by Github so it supports Github integration. It is often called the “hackable IDE of 21st century”, so you could easy customize almost everything.

Cool visual extension is “Power mode”, every time you hit a key, editor does a little move, like you hit the screen.

3. Geany

Geany is a lightweight IDE, aims to provide fast development environment. Features: filebrowser, save actions( autosave, instantsave, backupcopy), split window. In ubuntu you can install Geany using apt:

sudo apt-get install geany

4. Kate

It is a pre-installed text editor in Kubuntu. Some of the useful features: embedded terminal, SQL plugin, find and replace, syntax highlighting, bracket matching, auto backup, auto-completion with argument handling.