'bash'에 해당되는 글 20건

  1. 2019.03.11 [BASH] directory list
  2. 2019.02.22 [개발일반] git log stats --all 사용
  3. 2018.08.28 [Shell] 특정 크기 이상인 파일 찾기
  4. 2017.11.22 [Bash] for loop range and if condition
  5. 2017.09.28 [Shell] .bash_profile 기본 복붙.
  6. 2016.08.03 [Bash Script] ssh 접속 시 hostname 기준으로 편하게 사용하기.
  7. 2016.02.03 [bash] while true; loop...
  8. 2014.10.06 bash for loop...
  9. 2009.10.20 Shell Redirection
  10. 2008.12.30 [펌]bash script

[BASH] directory list

ITWeb/개발일반 2019. 3. 11. 19:16


명령어만 사용하던걸 스크립트에서 사용 할때)


#!/bin/bash


for i in $(ls -d */)

do

echo ${i%%/}

done


특정 디렉토리 아래에 있는 디렉토리 목록 출력. (이런 기본도 이제는 기록을 해둬야 ㅡ.ㅡ;)


참고로 for in 에서 간혹 실수 하는 것)


for (( idx=1; idx<=$PERIOD; idx++ ))

do

    echo "$idx 번 입니다."

done


$PERIOD 를 변수로 받아서 처리 할 경우 아래의 for .. in  은 동작을 안합니다.


for idx in {1..$PERIOD}

do

    echo "$idx 번 입니다."

done


:

[개발일반] git log stats --all 사용

ITWeb/개발일반 2019. 2. 22. 16:32

귀차니즘....

recursive 하게 submodule 가져와서도 해야 하는데...

--submodule


#!/usr/bin/env bash


git stash

git pull


DAYS_AGO=$1

DATE=`date -v -"$DAYS_AGO"d +%F`

PWD=`pwd`


echo "Date : $DATE" > "git-stats-$DATE.log"

echo "Date : $DATE" >> "git-stats-all.log"

# This script must exist under git repository.


echo "[Commit Statistics]" >> "git-stats-$DATE.log"

echo "[Commit Statistics]" >> "git-stats-all.log"

# total commit stats

USER_COUNT=`git log --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all --format='%aN %ce' | sort -u | wc -l`

echo "Total Commit Users : $USER_COUNT" >> "git-stats-$DATE.log"

echo "Total Commit Users : $USER_COUNT" >> "git-stats-all.log"

git log --shortstat --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all | grep -E "fil(e|es) changed" | awk '{files+=$1; inserted+=$4; deleted+=$6} END {print "files changed: ", files, "lines inserted: ", inserted, "lines deleted: ", deleted }' >> "git-stats-$DATE.log"

git log --shortstat --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all | grep -E "fil(e|es) changed" | awk '{files+=$1; inserted+=$4; deleted+=$6} END {print "files changed: ", files, "lines inserted: ", inserted, "lines deleted: ", deleted }' >> "git-stats-all.log"

echo "" >> "git-stats-$DATE.log"

echo "" >> "git-stats-all.log"


echo "[Committers]" >> "git-stats-$DATE.log"

echo "[Committers]" >> "git-stats-all.log"

# commit user list

git log --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all --format='%aN %ce' | sort -u >> "git-stats-$DATE.log"

git log --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all --format='%aN %ce' | sort -u >> "git-stats-all.log"

echo "" >> "git-stats-$DATE.log"

echo "" >> "git-stats-all.log"


echo "[Commit Logs]" >> "git-stats-$DATE.log"

echo "[Commit Logs]" >> "git-stats-all.log"

# each user commit stats

git log --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all --pretty=format:'"%an", "%aD", "%s",' --shortstat --no-merges >> "git-stats-$DATE.log"

git log --before="$DATE 23:59:59" --after="$DATE 00:00:00" --all --pretty=format:'"%an", "%aD", "%s",' --shortstat --no-merges >> "git-stats-all.log"


:

[Shell] 특정 크기 이상인 파일 찾기

ITWeb/개발일반 2018. 8. 28. 12:43

- 2MB 이상 파일 찾기

$ find * -size +2M -type f | wc -l


- 2MB 이상 파일 삭제 하기

$ find * -size +2M -type f -exec rm -f '{}' \;


args1 = <where to find>
args2 = <find by what, which means it could be -name, -type and here we give -size to mean we wish to find files by size>
args3 = <what size.. +10k would mean above 10 kilo bytes>
args4 = <and one more condition .. -type, which means what type of things should it match>
args5 = <-f means files.. we could have mentioned -d (directory) -b (block), -c (character), -f (regular file), -l (link), -s (socket), -p (pipes) >
args6 = <-exec means what action to perform if all the matches are true, so -exec is for action..>
args7..10 = < the following of -exec is a shell command..
rm -f {} \; this means the results of match is removed (deleted)>

:

[Bash] for loop range and if condition

ITWeb/개발일반 2017. 11. 22. 11:16

이런 간단한것도 매번 생각이 나지 않아서 기록해 봅니다.


$ for i in {1..10}

do

s3cmd get s3://part-$i

if [ $i -gt 9 ]

then

break

fi

done


:

[Shell] .bash_profile 기본 복붙.

ITWeb/개발일반 2017. 9. 28. 11:02

귀찮을때 복붙.


# .bash_profile


if [ -f ~/.bashrc ]; then

  source ~/.bashrc

fi


PATH=$HOME/bin:$PATH


export PATH

:

[Bash Script] ssh 접속 시 hostname 기준으로 편하게 사용하기.

ITWeb/개발일반 2016. 8. 3. 14:37

그냥 노가다 입니다.

ssh 접속 할때 dev/stage/prod 환경으로 각각 접속 할때 hostname 기준으로 하다 보면 매번 입력하기 귀찮은데요.

기억도 나지 않고, 그래서 노가다 스크립트 하나 만들었습니다.


변형해서 사용하거나 그냥 하드코딩 하거나 맘대로 사용하세요.


#!/bin/bash


SUFFIX='web'


echo '1) stage-web'

echo '2) prod-web'

... 중략


read choice


case $choice in

  1)

    SUFFIX='web'

    ;;

  2)

    SUFFIX='irc'

    ;;

... 중략

    ;;

  *)

    echo 'Choice number.'

    exit;

esac


echo "Connecting to ssh {PREFIX-NAME}-$SUFFIX"

sleep 1

ssh {PREFIX-NAME}-$SUFFIX


:

[bash] while true; loop...

ITWeb/개발일반 2016. 2. 3. 14:05

그냥 이런것도 기록합니다.


while true

do

    ps ef | grep mysqldump

    sleep 5

done


:

bash for loop...

ITWeb/개발일반 2014. 10. 6. 12:17

머리가 나빠서 맨날 까먹어요...ㅡ.ㅡ;;


일반적인 bash for loop..

for i in 1 2 3 4 5

do

    echo $i

done


start, end 를 가지는 for loop

START=1

END=5

for (( i=$START; i<=$END; i++ ))

do

    echo $i

done


while 문은 그냥 귀찮아서 pass, 필요 하면 구글링에게... ^^;

:

Shell Redirection

ITWeb/개발일반 2009. 10. 20. 14:20
man bash 하신 후 redirection 부분 참고 하시면 됩니다.

Handle Name Description
0 stdin Standard input
1 stdout Standard output
2 stderr Standard error

아래는 뽑아서 올려 놓은 거랍니다.. :)

REDIRECTION
       Before  a command is executed, its input and output may be redirected using a special notation inter-
       preted by the shell.  Redirection may also be used to open and close files for the current shell exe-
       cution environment.  The following redirection operators may precede or appear anywhere within a sim-
       ple command or may follow a command.  Redirections are processed in the order they appear, from  left
       to right.

       In  the  following descriptions, if the file descriptor number is omitted, and the first character of
       the redirection operator is <, the redirection refers to the standard input (file descriptor 0).   If
       the  first  character of the redirection operator is >, the redirection refers to the standard output
       (file descriptor 1).

       The word following the redirection operator in the following descriptions, unless otherwise noted, is
       subjected  to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic
       expansion, quote removal, pathname expansion, and word splitting.  If it expands  to  more  than  one
       word, bash reports an error.

       Note that the order of redirections is significant.  For example, the command

              ls > dirlist 2>&1

       directs both standard output and standard error to the file dirlist, while the command

              ls 2>&1 > dirlist

       directs  only the standard output to file dirlist, because the standard error was duplicated as stan-
       dard output before the standard output was redirected to dirlist.

       Bash handles several filenames specially when they are used in redirections, as described in the fol-
       lowing table:

              /dev/fd/fd
                     If fd is a valid integer, file descriptor fd is duplicated.
              /dev/stdin
                     File descriptor 0 is duplicated.
              /dev/stdout
                     File descriptor 1 is duplicated.
              /dev/stderr
                     File descriptor 2 is duplicated.
              /dev/tcp/host/port
                     If  host is a valid hostname or Internet address, and port is an integer port number or
                     service name, bash attempts to open a TCP connection to the corresponding socket.
              /dev/udp/host/port
                     If host is a valid hostname or Internet address, and port is an integer port number  or
                     service name, bash attempts to open a UDP connection to the corresponding socket.

       A failure to open or create a file causes the redirection to fail.

       Redirections  using  file  descriptors  greater than 9 should be used with care, as they may conflict
       with file descriptors the shell uses internally.

   Redirecting Input
       Redirection of input causes the file whose name results from the expansion of word to be  opened  for
       reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.

       The general format for redirecting input is:

              [n]<word

   Redirecting Output
       Redirection  of output causes the file whose name results from the expansion of word to be opened for
       writing on file descriptor n, or the standard output (file descriptor 1) if n is not  specified.   If
       the file does not exist it is created; if it does exist it is truncated to zero size.

       The general format for redirecting output is:
              [n]>word

       If  the  redirection operator is >, and the noclobber option to the set builtin has been enabled, the
       redirection will fail if the file whose name results from the expansion of word exists and is a regu-
       lar  file.   If  the  redirection  operator is >|, or the redirection operator is > and the noclobber
       option to the set builtin command is not enabled, the redirection is attempted even if the file named
       by word exists.

   Appending Redirected Output
       Redirection  of  output in this fashion causes the file whose name results from the expansion of word
       to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if  n  is
       not specified.  If the file does not exist it is created.

       The general format for appending output is:

              [n]>>word

   Redirecting Standard Output and Standard Error
       Bash allows both the standard output (file descriptor 1) and the standard error output (file descrip-
       tor 2) to be redirected to the file whose name is the expansion of word with this construct.

       There are two formats for redirecting standard output and standard error:

              &>word
       and
              >&word

       Of the two forms, the first is preferred.  This is semantically equivalent to

              >word 2>&1

   Here Documents
       This type of redirection instructs the shell to read input from the current source until a line  con-
       taining only word (with no trailing blanks) is seen.  All of the lines read up to that point are then
       used as the standard input for a command.

       The format of here-documents is:

              <<[-]word
                      here-document
              delimiter

       No parameter expansion, command substitution, arithmetic expansion, or  pathname  expansion  is  per-
       formed  on  word.  If any characters in word are quoted, the delimiter is the result of quote removal
       on word, and the lines in the here-document are not expanded.  If word is unquoted, all lines of  the
       here-document  are  subjected to parameter expansion, command substitution, and arithmetic expansion.
       In the latter case, the character sequence \<newline> is ignored, and \ must be  used  to  quote  the
       characters \, $, and  ?

       If the redirection operator is <<-, then all leading tab characters are stripped from input lines and
       the line containing delimiter.  This allows here-documents within shell scripts to be indented  in  a
       natural fashion.

   Here Strings
       A variant of here documents, the format is:

              <<<word

       The word is expanded and supplied to the command on its standard input.

   Duplicating File Descriptors
       The redirection operator

              [n]<&word

       is  used  to  duplicate  input  file  descriptors.   If  word expands to one or more digits, the file
       descriptor denoted by n is made to be a copy of that file descriptor.  If the digits in word  do  not
       specify  a  file descriptor open for input, a redirection error occurs.  If word evaluates to -, file
       descriptor n is closed.  If n is not specified, the standard input (file descriptor 0) is used.

       The operator

              [n]>&word

       is used similarly to duplicate output file descriptors.  If n is not specified, the  standard  output
       (file descriptor 1) is used.  If the digits in word do not specify a file descriptor open for output,
       a redirection error occurs.  As a special case, if n is omitted, and word does not expand to  one  or
       more digits, the standard output and standard error are redirected as described previously.

   Moving File Descriptors
       The redirection operator

              [n]<&digit-

       moves  the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n
       is not specified.  digit is closed after being duplicated to n.

       Similarly, the redirection operator
       [n]>&digit-

       moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n
       is not specified.

   Opening File Descriptors for Reading and Writing
       The redirection operator

              [n]<>word

       causes the file whose name is the expansion of word to be opened for both reading and writing on file
       descriptor n, or on file descriptor 0 if n is not specified.  If the file does not exist, it is  cre-
       ated.

:

[펌]bash script

ITWeb/개발일반 2008. 12. 30. 14:45

원본 URL : http://www.linuxconfig.org/Bash_scripting_Tutorial
참고 사이트 : http://www.unix.com/


This bash script tutorial assumes no previous knowledge of bash scripting.As you will soon discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is very easy task. Lets begin this bash scripting tutorial with a simple "Hello World" script.

Recommended Books / Reading on this topic :

Learning the bash Shell: Unix Shell Programming]

Hello World Bash Shell Script

First you need to find out where is your bash interpreter located. Enter the following into your command line:

$ which bash
bash interpreter location: /bin/bash

Open up you favorite text editor ( Here is a tutorial where you can learn how to use vi / vim text editor. ) and a create file called hello_world.sh. Insert the following lines to a file:

<b>NOTE:Every bash shell script in this tutorial starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.

Here is our first bash shell script example:

#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING

Example of simple bash shell script

Navigate to a directory where your hello_world.sh is located and make the file executable:

$ chmod +x hello_world.sh
Make bash shell script executable

Now you are ready to execute your first bash script:

./hello_world.sh
execute bash shell script


Simple Backup bash shell script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig
Simple Backup bash script

Variables

In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command.

#!/bin/bash
STRING="HELLO WORLD!!!"
echo $STRING
String Variables in bash script

Your backup script and variables:

#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
tar -czf $OF /home/linuxconfig
Bash backup Script with Variables

Global vs. Local variables

#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"
function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR
Global vs. Local variables in bash script

Passing arguments to the bash script

#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once
echo $@ ' -> echo $@'

# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'
./arguments.sh Bash Scripting Tutorial
Passing arguments to the bash script

Executing shell commands with bash

#!/bin/bash

# use backticks " ` ` " to execute shell command
echo `uname -o`
# executing bash command without backticks
echo uname -o

Executing shell commands with bash

Reading User Input

#!/bin/bash

echo -e "Hi, please type the word: \c "
read  word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
Reading User Input with bash

Bash Trap Command

#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
    echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
    echo "$a/10 to Exit." 
    sleep 1;
done
echo "Exit Bash Trap Example!!!"

Arrays

Declare simple bash array

#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array 
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
    echo ${ARRAY[${i}]}
done
Declare simple bash array

Read file into bash array

#!/bin/bash
#Declare array 
declare -a ARRAY
#Open file for reading to array
exec 10<bash.txt
let count=0

while read LINE <&10; do

    ARRAY[$count]=$LINE
    ((count++))
done

echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# close file 
exec 10>&-
Read file into bash array

Bash if/else statements

Simple Bash if/else statement

Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!

#!/bin/bash
directory="./BashScripting"

# bash check if directory exists
if [ -d $directory ]; then
	echo "Directory exists"
else 
	echo "Directory does not exists"
fi

Bash if else statement

Nested if/else

#!/bin/bash

# Declare variable choice and assign value 4
choice=4
# Print to stdout
 echo "1. Bash"
 echo "2. Scripting"
 echo "3. Tutorial"
 echo -n "Please choose a word [1,2 or 3]? "
# Loop while the variable choice is equal 4
# bash while loop
while [ $choice -eq 4 ]; do

# read user input
read choice
# bash nested if/else
if [ $choice -eq 1 ] ; then

        echo "You have chosen word: Bash"

else                   

        if [ $choice -eq 2 ] ; then
                 echo "You have chosen word: Scripting"
        else
         
                if [ $choice -eq 3 ] ; then
                        echo "You have chosen word: Tutorial"
                else
                        echo "Please make a choice between 1-3 !"
                        echo "1. Bash"
                        echo "2. Scripting"
                        echo "3. Tutorial"
                        echo -n "Please choose a word [1,2 or 3]? "
                        choice=4
                fi   
        fi
fi
done
Nested Bash if else statement

Bash Comparisons

Arithmetic Comparisons

-lt
<
-gt
>
-le
<=
-ge
>=
-eq
==
-ne
!=
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
else 
	echo "Values are NOT equal"
fi
Bash Arithmetic Comparisons - values are equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
else 
	echo "Values are NOT equal"
fi
Bash Arithmetic Comparisons - values are NOT equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if   [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
elif [ $NUM1 -gt $NUM2 ]; then
	echo "NUM1 is greater then NUM2"
else 
	echo "NUM2 is greater then NUM1"
fi
Bash Arithmetic Comparisons - greater then

String Comparisons

=
equal
 !=
not equal
<
less then
>
greater then
-n s1
string s1 is not empty
-z s1
string s1 is empty
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
	echo "Both Strings are equal"
else 
	echo "Strings are NOT equal"
fi
Bash String Comparisons - values are NOT equal
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Bash"
if [ $S1 = $S2 ]; then
	echo "Both Strings are equal"
else 
	echo "Strings are NOT equal"
fi
Bash String Comparisons - values are equal

Bash File Testing

-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable
#!/bin/bash
file="./file"
if [ -e $file ]; then
	echo "File exists"
else 
	echo "File does not exists"
fi
Bash File Testing - File does not exist
Bash File Testing - File exists

Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option.

#!/bin/bash

while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done

Loops

Bash for loop

#!/bin/bash

# bash for loop
for f in $( ls /var/ ); do
	echo $f
done

Running for loop from bash shell command line:

$ for f in $( ls /var/ ); do echo $f; done
Bash for loop

Bash while loop

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
	echo Value of count is: $COUNT
	let COUNT=COUNT-1
done
Bash while loop

Bash until loop

#!/bin/bash
COUNT=0
# bash until loop
until [ $COUNT -gt 5 ]; do
        echo Value of count is: $COUNT
        let COUNT=COUNT+1
done
Bash until loop

Control bash loop with <STDIN>

Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues.

#!/bin/bash
# This bash script will locate and replace spaces
# in the filenames
DIR="."
# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find $DIR -type f | while read file; do
# using POSIX class [:space:] to find space in the filename
if [[ "$file" = *[[:space:]]* ]]; then
# substitute space with "_" character and consequently rename the file
mv "$file" `echo $file | tr ' ' '_'`
fi;
# end of while loop
done

Bash script to replace spaces in the filenames with _

Bash Functions

!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
        echo Function B.
}
function function_A {
        echo $1
}
function function_D {
        echo Function D.
}
function function_C {
        echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D
Bash Functions

Bash Select

#!/bin/bash

PS3='Choose one word: ' 

# bash select
select word in "linux" "bash" "scripting" "tutorial" 
do
  echo "The word you have selected is: $word"
# Break, otherwise endless loop
  break  
done

exit 0
Bash Select

Case statement conditional

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in
    1) echo "You selected bash";;
    2) echo "You selected perl";;
    3) echo "You selected phyton";;
    4) echo "You selected c++";;
    5) exit
esac

bash case statement conditional

Bash quotes and quotations

Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.

Escaping Meta characters

Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash "\" character. Example:

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR 

# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\"

escaping meta characters in bash

Single quotes

Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters special meaning in bash is suppressed when  using single quotes 
echo '$BASH_VAR  "$BASH_VAR"'

Using single quotes in bash

Double Quotes

Double quotes in bash will suppress special meaning of every meta characters except "$", "\" and "`". Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with "\". Example:

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters and its special meaning in bash is 
# suppressed when using double quotes except "$", "\" and "`"

echo "It's $BASH_VAR  and \"$BASH_VAR\" using backticks: `date`"

Using double quotes in bash

Bash quoting with ANSI-C style

There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with "\" will gain special meaning according to the ANSI-C standard.

/a
alert (bell)
/b
backspace
/e
an escape character
/f
form feed
/n
newline
/r
carriage return
/t
horizontal tab
/v
vertical tab
\\
backslash
\`
single quote
\nnn
octal value of characters ( see ASCII table )
\xnn
hexadecimal value of characters ( see ASCII table )

The syntax fo ansi-c bash quoting is: $'<your string>' . Here is an example:

#!/bin/bash

# as a example we have used \n as a new line, \x40 is hex value for @
# and \56 is octal value for .
echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org'

quoting in bash with ansi-c stype

Arithmetic Operations

Simple Bash Addition Calculator Example

#!/bin/bash

let RESULT1=$1+$2
echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2'
declare -i RESULT2
RESULT2=$1+$2
echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2'
echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))'

Bash Addition Calculator

Bash Arithmetics

#!/bin/bash

echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION 

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ] 
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result
Arithmetic Operations


Round floating point number

#!/bin/bash
# get floating point number
floating_point_number=3.3446
echo $floating_point_number
# round floating point number with bash
for bash_rounded_number in $(printf %.0f $floating_point_number); do
echo "Rounded number with bash:" $bash_rounded_number
done

Round floating point number with bash

Bash floating point calculations

#!/bin/bash
# Simple linux bash calculator 
echo "Enter input:" 
read userinput
echo "Result with 2 digits after decimal point:"
echo "scale=2; ${userinput}" | bc 
echo "Result with 10 digits after decimal point:"
echo "scale=10; ${userinput}" | bc 
echo "Result as rounded integer:"
echo $userinput | bc

Bash floating point calculations

Redirections

STDOUT from bash script to STDERR

#!/bin/bash

echo "Redirect this STDOUT to STDERR" 1>&2

To proof that STDOUT is redirected to STDERR we can redirect script's output to file:

STDOUT from bash script to STDERR

STDERR from bash script to STDOUT

#!/bin/bash

cat $1 2>&1

To proof that STDERR is redirected to STDOUT we can redirect script's output to file:

STDERR from bash script to STDOUT

stdout to screen

The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen.

cat /proc/partitions
bash stdout to screen

stdout to file

Here we use ">" to redirect stdout to a file "partitions.txt".

cat /proc/partitions > partitions.txt
bash stdout to file

stderr to file

In this example you will redirect the standard error ( stderr ) to a file and stdout to a default screen.

grep -r hda6 * . 2> stderr.txt
bash stderr to file

stdout to stderr

In this case the output of a command will be written to the same descriptor as a stderr.

grep -r hda6 * . 1>&2 stderr.txt
bash stdout to stderr

stderr to stdout

In this case the stderr of a command will be written to the same descriptor as a stdout.

grep -r hda6 * . 2>&1 stderr.txt
stderr to stdout

stderr and stdout to file

grep -r hda6 * . &> stderr_and_stdout.txt
stderr and stdout to file
: