Bash: Redirection from file to command

We can redirect the contents of one file descriptor to another. By using redirection, we can read data from a file as stdin as follows:

$ cmd < file

Source: Linux Shell Scripting Cookbook

Comments { 0 }

Bash: Check for super user

UID is an important environment variable that can be used to check whether the current script has been run as root user or regular user. For example:

if [ $UID -ne 0 ]; then
    echo "Non root user. Please run as root."
else
    echo "Root user"
fi

The UID for the root user is 0.

Source: Linux Shell Scripting Cookbook

Comments { 0 }

Bash: Identifying the current shell

Display the currently used shell as follows:

echo $SHELL

Or, you can also use:

echo $0

For example:

$ echo $SHELL
/bin/bash
$ echo $0
-bash

Source: Linux Shell Scripting Cookbook

Comments { 0 }

Bash: Finding length of string

Get the length of a variable value as follows:

length=${#var}

For example:

$ var=linuxrecipes.com
$ echo ${#var}
16

length is the number of characters in the string.

Source: Linux Shell Scripting Cookbook

Comments { 0 }