DEV Community

Cover image for Let's revel the power of Bash!
Krunal Kanojiya
Krunal Kanojiya

Posted on • Edited on • Originally published at techalgospotlight.com

Let's revel the 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!
Enter fullscreen mode Exit fullscreen mode

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

$ bash hello.sh
Enter fullscreen mode Exit fullscreen mode

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


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)

Enter fullscreen mode Exit fullscreen mode

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
'
Enter fullscreen mode Exit fullscreen mode

As you know every programming language have two types of comments, Single Line and Multiline. 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
$_
Enter fullscreen mode Exit fullscreen mode

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`"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 ))
Enter fullscreen mode Exit fullscreen mode

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 ]]
Enter fullscreen mode Exit fullscreen mode

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 ]]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
# If OPTION is enabled
[[ -o noclobber ]]

# Not
[[ ! EXPR ]]

# And
[[ X && Y ]]

# Or
[[ X | | Y ]]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

7. The Brace Expressions in Bash?

echo {A,B}.js
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Brace expressions nothing like just an Maths. If you know maths than you can relate.


8. Functions in Bash

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

get_name() {
    echo "Idiot"
}

echo "You are $(get_name)"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Returning Values

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

result="$(myfunc)"
Enter fullscreen mode Exit fullscreen mode

Raising Errors

myfunc() {
    return 1
}

if myfunc; then
    echo "success"
else
    echo "failure"
fi
Enter fullscreen mode Exit fullscreen mode

Bash Parameter expansions

Syntex

# 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}
Enter fullscreen mode Exit fullscreen mode

Substrings

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

# Substring from the right
${FOO:(-3):3}
Enter fullscreen mode Exit fullscreen mode

Length

# Length of $FOO
${#FOO}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Basepath & Dirpath in Bash

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

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


DIRPATH=${SRC%$BASEPATH}
echo $DIRPATH   # => "/path/to/"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

There are a few mistakes here, and they're going to be a little difficult for a newbie to spot since you don't explain why you choose a particular syntax for each example.

In #5, $(PWD) will fail with command-not-found because PWD isn't a command. It should be $(pwd) or ${PWD}.

In #6, [[ X | | Y ]] is going to explode because of the extra space, and it's confusing what you're representing with X and Y in this example.

For simple conditionals, single-bracket syntax is good, e.g. [ -f /tmp/foo ] since this is POSIX and will work on other shells. Double-brackets might or might not, depending on the shell. Similarly, using printf rather than echo will make what you suggest in this post work on any other POSIX shell.

In one of the others you mention -e as a test for "file exists" and that's correct, but it'd be better to use -f in 99% of cases since -e will return true even if the file is actually a directory.

Collapse
 
imkrunalkanojiya profile image
Krunal Kanojiya

You have opportunity to recreate this article and more informative. ๐Ÿ˜๐Ÿ˜