DEV Community

Zaki Arrozi Arsyad
Zaki Arrozi Arsyad

Posted on

linux : bash script

We can run the bash script directly in the terminal.

$ echo "This is a bash script."
This is a bash script.
Enter fullscreen mode Exit fullscreen mode

We also can store the script in a file, so that we can run it every time we want without typing the script in terminal.

# !/bin/bash
echo "This is a bash script." 
Enter fullscreen mode Exit fullscreen mode

We need to update the file permission if we want to run the bash file. We can run this command, and specify the file permission

$ chmod 700 FILE
$ ./FILE
This is a bash script.
Enter fullscreen mode Exit fullscreen mode

We can run linux command in bash file and run the bash script in the cli.


The bash file will very useful if we want to use some variable or put logics in the script.


VARIABLE

  • Positional Parameter Variable
# !/bin/bash
echo "This is a $1 $2." 
Enter fullscreen mode Exit fullscreen mode

we can give a value for $1 and $2 after the run command.

$ ./FILE bash script
Enter fullscreen mode Exit fullscreen mode
  • User Defined Variable
# !/bin/bash
# define a string value, print as is
print1='script'

# define a string value, we can add variable inside the double quotes
print2="bash $print1"

# define a number
print3=3

# define a command
print4=`clear`

echo $script
Enter fullscreen mode Exit fullscreen mode
  • Environment Variable

Usually we use .env file to store the environment variable

PORT=80
ENV=development
Enter fullscreen mode Exit fullscreen mode

operation for variable

# using let
let sum=$number1+$number2

# using expr
sum=`expr $number1 + $number2`
length=`expr length $string`
Enter fullscreen mode Exit fullscreen mode

declaring variable type

# declare an intrger
declare -i number
number=100
Enter fullscreen mode Exit fullscreen mode

IF STATEMENT

if [ CONDITION ]; then
    TRUE_COMMANDS
else
    FALSE_COMMANDS
fi
Enter fullscreen mode Exit fullscreen mode

WHILE LOOPING

while [ CONDITION ]
do
    COMMANDS
done
Enter fullscreen mode Exit fullscreen mode

FOR LOOPING

for VARIABLE in LIST
do
    COMMANDS
done
Enter fullscreen mode Exit fullscreen mode

Top comments (0)