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

Bash How to Add Numbers

Bash How to Add Numbers

Bash provides a lot of methods how to add numbers. First of all is use $(())

echo $((2+2+1))

Output: 5

If we have a variable which has an integer value, we can use “$var”:

var=5
echo $((6+$var))

Output: 11

We can assign to variable counted numbers:

var=$((3+6))

The value of “var” is 9 now.

Another arithmetic expansion:
var=$((num1 + num2))
var=$(($num + $num2))
var=$((num1 + 10 + 20))
var=$[num1+num2]

Bash How to get Yesterday’s Date

Bash How to get Yesterday’s Date

Date command has d parameter, that displays time described after d parameter:

date -d yesterday '+%Y-%m-%d'

%Y means year, %m means month, and %d means day. You can change formatting if you want:

date -d yesterday '+%Y:%m:%d'

What if you want get several days, for example, day before 5 days?

date +%Y-%m-%d -d "5 day ago"

Would you take yesterday’s date to the variable?

YESTERDAY=`date -d yesterday '+%Y-%m-%d'`
echo $YESTERDAY

Alternative way is using hours:

date -d "24 hours ago" '+%Y-%m-%d'

Another way:

date --date='-1 day' '+%Y-%m-%d'

Bash How to Quit a Script

Bash How to Quit a Script

The command “exit” terminate the script and return value:

Every command returns an exit status, sometimes it is called exit code or return status.

0: Script was executed with success.

1 and greater: Script was executed with error. The non-zero return value is interpreted as an “error code”.

If you want to get the exit value last executed script use $?.

./script.sh
echo $?

Sometimes you can see exit $? which is equivalent to exit.

Bash Vs KSH

Bash Vs KSH

Linux and Unix have various shells. Two kinds of these numerous shells are KSH and BASH.

KSH (The Korn Shell) was developed many years before the BASH. Ksh has associative arrays and handles loop syntax better than bash. Also, ksh’s command print is better than bash’s echo command. In other way, ksh does not support history completion, process substitution, and rebindable command-line editing.

Bash has more added extension than ksh. Bash has tab completion and an easier method to set a prompt in order to display the current directory.

Compared to ksh, bash is newer and more popular.

Example of difference ksh and bash in condition test. First bash:

if [ $i -eq 3 ]

and condition test in ksh:

if (($i==3))

Bash can handle exit codes from pipes in a cleaner way. Bash and KSH are both Bourne=compatible shells, they share common functions and features and can be interchangeable to use.

Bash How to Check If File Exists

Bash How to Check If File Exists

What is the definition file in Linux? The file is almost everything – keyboard, and disk, and the regular file. Here is an example of a regular file: document.odt or /etc/passwd.

If you want the script to find out if there is any file (eg. tile.txt or /dev/sda), you can do the following:

if [ -e /root/file.txt ]; then
echo "File found";
fi

So, we tested if any kind of file (named /root/file.txt) exists.

If you want to take into consideration just regular files (not /dev/sda but just /root/file.txt), you can use -f parameter instead of -e parameter:

if [ -f /root/file.txt ]; then
echo "Regular file found";
fi

If you want to check, if a regular file not exists, you can use not(!) in test command []:

if [ ! -f /root/file.txt ]; then
echo "Regular file not found";
fi

We could tune the last example. You can also use short way how to write it:

[ ! -f /root/file.txt ] && echo "Regular file not found"

It is my favorite if you have just one command after the test command.

Here are some examples of file test operators:

Option Test
-s File is a regular file (if the file is directory or device returns false)
-d File is a directory
-b File is a block device
-c File is a character device
-p File is a pipe
-w File has a write permission