HyunsooZo's TIL logo HyunsooZo's TIL

Shell Script?

A shell script is a program written in a scripting language that can be executed by a Unix/Linux shell. It consists of a sequence of commands, and can be used to automate tasks, manipulate files, perform system administration tasks, and more. Shell scripts are commonly used in system administration, software deployment, and other tasks that require automating a series of commands in a Unix/Linux environment.

hyunsoojo@HYUNSOOui-MacBook-Pro:~$vi hello.sh
# echo(shell method) "Hello bash!" -> :wq! 

hyunsoojo@HYUNSOOui-MacBook-Pro:~$ls -al
# -rw-r--r--    1 hyunsoojo  staff      33  5  3 19:03 hello.sh

hyunsoojo@HYUNSOOui-MacBook-Pro:~$chmod 764 hello.sh
hyunsoojo@HYUNSOOui-MacBook-Pro:~$ls -al
# -rwxrw-r--    1 hyunsoojo  staff      33  5  3 19:03 hello.sh

hyunsoojo@HYUNSOOui-MacBook-Pro:~$ ./hello.sh
# Hello bash!    <- will be printed

Variable declaration

variable declaration ->name = "whatever"
use variable -> $name

#!/bin/bash

mysql_id='root'
mysql_directory='/ect/mysql'

echo $mysql_id      
echo $mysql_directory

Pre-declared Variables

$0: This variable contains the name of the shell script or the current shell.

$1-$9: These variables contain the first 9 arguments passed to the script. $1 contains the first argument, $2 the second, and so on.

$*: This variable contains all the arguments passed to the script as a single string. Each argument is separated by the first character in the $IFS (Internal Field Separator) variable.

$#: This variable contains the number of arguments passed to the script.

$?: This variable contains the exit status of the last executed command. A value of 0 indicates success, and a non-zero value indicates an error or failure.

Array

#!/bin/bash

daemons =("httpd" "mysqld" "vsftpd")
acho ${daemons[*]}

output will be -> httpd mysqld vsftpd

Operator

expr -> number operation

#!/bin/bash

num=`expr \(3 \* 5 \) 4 \+ 7`
scho $num

output will be -> 10

Conditional

if [ condition ]
then
    action
fi

val1 -eq val2 -> equal
val1 -ne val2 -> not equal
val1 -lt val2 -> less then
val1 -le val2 -> less or equal
val1 -gt val2 -> greater than
val1 -ge val2 -> greater or equal

Sample

#!/bin/bash

ping -c 1 192.168.0.1 1> /dev/null
if [ $? == 0 ]
then
    echo 'succeed'
else 
    scho 'failed'
fi

output will be -> succeed (or failed)

Loop

for [variable] in var1 var2 ...
do
    action
done

Example

#!/bin/bash

for database in $(ls)
do
    echo $database
done

output will be ls's content

TOP