Bash Color Shell Prompt

Bash Color Shell Prompt

You can customize 4 prompts: PS1 (Primary prompt, displayed before each command), PS2 (secondary prompt, displayed when a command needs more input), PS3 (rarely used, displayed for Bash’s select built-in which displays interactive menus).

Display current bash prompt (PS1) settings:

echo $PS1

Output: [\u@\h \W]\$

It is the default setting. The backslash-escaped characters means: \u (username), \h (hostname), \W (current working directory).

To modify colors to the prompt use following syntax:

\e[x;ym $PS1 \e[m

Meaning: \e[ (start color scheme), x;y (color pair to use), $PS1 (shell prompt variable), \e[m (stop color scheme)

To set red color enter:

export PS1="\e[0;36m[\u@\h \W]\$ \e[m "

Few examples of color codes:

  • black(0;30)
  • red (0;31)
  • greed (0;32)
  • brown (0;33)
  • blue (0;34)
  • purple (0:35)
  • cyan (0:36)

If you replace digit 0 with 1 you get a lighter color version.
Setting variable PS1 is temporary, when you log out your settings will be lost. You have to append the following line to $HOME/.bash_profile file or $HOME/.bashrc file:

export PS1="\e[0;36m[\u@\h \W]\$ \e[m "

Now ur new prompt color is permanent.

Bash How to Pass Arguments

Bash How to Pass Arguments

The special shell variable “$@” represents a list of all arguments that is passed to the script.

If you want to pass all arguments to your function, you can use this syntax:

function_name "$@"

If you want to pass all arguments to another script, you can use this syntax:

script_mame "$@"

Let’s take an example called passit.sh. In this script, we defined function print_argument, that print argument that comes from the command line:

#!/bin/bash

# function's definition
function PRINT_ARGUMENTS()
{
echo "Arguments of shell are: $@"
}

# in this place we want to call function
PRINT_ARGUMENTS "$@"

Let’s try to execute passit.sh in this way:

chmod u+x ./passit.sh
./passit.sh aa bb cc

Output: Arguments of the shell are: aa bb cc

You can see that function obtains all shell arguments, which were written in the bash command line.

To get a number of arguments use:

echo "Number of arguments of shell are: $#"

It is often used to check if a required number is equal to some value.

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