Let’s Revel Power of Bash!

Bash is the one of the core and most useful medium to communicate with kernel. You can say Operating System. Maybe Linux or Windows or Rich Peoples MacOS.

We never know, if we can not try see what actually bash can do. And how much capable bash is. So, Instead of Wasting time in chitchat, Let’s me show you the power of Bash with example.

1. Hello World in bash

#!/bin/bash

VAR="world"
echo "Hello $VAR!" # => Hello world!

First program of any programming language. Let’s execute.

$ bash hello.sh

What do you think, What is the output. Of Course Hello World 😀


2. Variables in Bash

NAME="John"

echo ${NAME}    # => John (Variables)
echo $NAME      # => John (Variables)
echo "$NAME"    # => John (Variables)
echo '$NAME'    # => $NAME (Exact string)
echo "${NAME}!" # => John! (Variables)

NAME = "John"   # => Error (about space)

For output, you have to execute this script. Anyway this is how we can create variables in bash and save as .sh file.


3. Most Popular, Comments in Bash

# This is an inline Bash comment.

: '
This is a
very neat comment
in bash
'

As you know every programming language have two types of comments, Single Line and Multi line. Nothing Extra.


4. Arguments in Bash

There is multiple arguments available in bash. but as human i am able to memories some of them. Let me share.

# Parameter 1 ... 9
$1 … $9 

# Name of the script itself
$0

# First argument
$1

# Positional parameter 10
${10}

# Number of arguments
$#

# Process id of the shell
$$

# All arguments
$*

# All arguments, starting from first
$@   

# Current options
$-

# Last argument of the previous command
$_

As of now i know this many arguments only. If you want to see more then i really recommend perplexity AI app (No Promotion).

With this argument’s let’s execute some of the command with text.


5. Bash Shell Execution

# => I'm in /path/of/current
echo "I'm in $(PWD)"

# Same as:
echo "I'm in `pwd`"

This is just an print current directory. Nothing else. Nothing Fancy. Simple!


6. Conditionals in Bash

if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
fi

Bash have very unique syntax for conditionals. if is readable but else if is like elif and fi. anyway, this is what it is. bash is bash!

Bash have some more and cool conditionals features like Integral Conditions, Strings Conditions, File Conditions and many more. Let’ share each of them one by one.

Integer Conditions

# Equal
[[ NUM -eq NUM ]]

# Not equal
[[ NUM -ne NUM ]]

# Less than
[[ NUM -lt NUM ]]

# Less than or equal
[[ NUM -le NUM ]]

# Greater than
[[ NUM -gt NUM ]]

# Greater than or equal
[[ NUM -ge NUM ]]

# Less than
(( NUM < NUM ))

# Less than or equal
(( NUM <= NUM ))

# Greater than
(( NUM > NUM ))

# Greater than or equal
(( NUM >= NUM ))

String Conditions

# Empty string
[[ -z STR ]]

# Not empty string
[[ -n STR ]]

# Equal
[[ STR == STR ]]

# Equal (Same above)
[[ STR = STR ]]

# Less than (ASCII)
[[ STR < STR ]]

# Greater than (ASCII)
[[ STR > STR ]]

# Not Equal
[[ STR != STR ]]

# Regexp
[[ STR =~ STR ]]

File Conditions

# Exists
[[ -e FILE ]]

# Directory
[[ -d FILE ]]

# File
[[ -f FILE ]]

# Symlink
[[ -h FILE ]]

# Size is > 0 bytes
[[ -s FILE ]]

# Readable
[[ -r FILE ]]

# Writable
[[ -w FILE ]]

# Executable
[[ -x FILE ]]

# f1 newer than f2
[[ f1 -nt f2 ]]

# f2 older than f1
[[ f1 -ot f2 ]]

# Same files
[[ f1 -ef f2 ]]

logical and, OR Conditions

if [ "$1" = 'y' -a $2 -gt 0 ]; then
    echo "yes"
fi

if [ "$1" = 'n' -o $2 -lt 0 ]; then
    echo "no"
fi
# If OPTION is enabled
[[ -o noclobber ]]

# Not
[[ ! EXPR ]]

# And
[[ X && Y ]]

# Or
[[ X | | Y ]]

More Examples

# String
if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
else
    echo "This never happens"
fi

# Combinations
if [[ X && Y ]]; then
    ...
fi

# Equal
if [[ "$A" == "$B" ]]; then
    ...
fi

# Regex
if [[ '1. abc' =~ ([a-z]+) ]]; then
    echo ${BASH_REMATCH[1]}
fi

# Smaller
if (( $a < $b )); then
   echo "$a is smaller than $b"
fi

# Exists
if [[ -e "file.txt" ]]; then
    echo "file exists"
fi

7. The Brace Expressions in Bash

echo {A,B}.js

Bash have one Brace expressions feature. Basically that can compare the values. Let me share more about this.

# Same as A B
{A,B}

# Same as A.js B.js
{A,B}.js

# Same as 1 2 3 4 5
{1..5}

Brace expressions nothing like just an Mathe. If you know math than you can relate.


8. Functions in Bash

Very popular topic for every programming language and very tricky with their own behavior and execution style.

get_name() {
    echo "Idiot"
}

echo "You are $(get_name)"

I hope you are not an get_name. Also their is more things you can do with functions. As of now let’s divide into Three Part. Defining Functions, Returning Values and Raising Errors. Let me share each of them example.

Defining Function

myfunc() {
    echo "hello $1"
}

# Same as above (alternate syntax)
function myfunc() {
    echo "hello $1"
}

myfunc "John"

Returning Values

myfunc() {
    local myresult='some value'
    echo $myresult
}

result="$(myfunc)"

Raising Errors

myfunc() {
    return 1
}

if myfunc; then
    echo "success"
else
    echo "failure"
fi

9. Bash Parameter expansions

Syntax

# Remove suffix
${FOO%suffix}

# Remove prefix
${FOO#prefix}

# Remove long suffix
${FOO%%suffix}

# Remove long prefix
${FOO##prefix}

# Replace first match
${FOO/from/to}

# Replace all
${FOO//from/to}

# Replace suffix
${FOO/%from/to}

# Replace prefix
${FOO/#from/to}

Sub-strings

# Substring (position, length)
${FOO:0:3}

# Substring from the right
${FOO:(-3):3}

Length

# Length of $FOO
${#FOO}

Default values

# $FOO, or val if unset
${FOO:-val}

# Set $FOO to val if unset
${FOO:=val}

# val if $FOO is set
${FOO:+val}

# Show message and exit if $FOO is unset
${FOO:?message}

10. Substitution

echo ${food:-Cake}  #=> $food or "Cake"

STR="/path/to/foo.cpp"
echo ${STR%.cpp}    # /path/to/foo
echo ${STR%.cpp}.o  # /path/to/foo.o
echo ${STR%/*}      # /path/to

echo ${STR##*.}     # cpp (extension)
echo ${STR##*/}     # foo.cpp (basepath)

echo ${STR#*/}      # path/to/foo.cpp
echo ${STR##*/}     # foo.cpp

echo ${STR/foo/bar} # /path/to/bar.cpp

11. Base path & Dir path in Bash

SRC="/path/to/foo.cpp"

BASEPATH=${SRC##*/}
echo $BASEPATH  # => "foo.cpp"


DIRPATH=${SRC%$BASEPATH}
echo $DIRPATH   # => "/path/to/"

12. Slicing

name="John"
echo ${name}           # => John
echo ${name:0:2}       # => Jo
echo ${name::2}        # => Jo
echo ${name::-1}       # => Joh
echo ${name:(-1)}      # => n
echo ${name:(-2)}      # => hn
echo ${name:(-2):2}    # => hn

length=2
echo ${name:0:length}  # => Jo

13. Transform

STR="HELLO WORLD!"
echo ${STR,}   # => hELLO WORLD!
echo ${STR,,}  # => hello world!

STR="hello world!"
echo ${STR^}   # => Hello world!
echo ${STR^^}  # => HELLO WORLD!

ARR=(hello World)
echo "${ARR[@],}" # => hello world
echo "${ARR[@]^}" # => Hello World

This is not an end, There is still so many things are missing to share with you guys. Don’t worry, I will write second part of Bash!. I Hope you love it!

to be continued……

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply