Home tmade.de

Home Wiki

Variabel

variabel=value
echo $variabel

Debug

Set

set -x

Unset

set +x

IF/ELSE

The “if” syntax is dependant on the kind of condition. Basically there are 3 types:

1. file
2. integer
3. string

File

Example “file”:

file=/test
if [  -e $file ]
then
echo "$file exist."
else
echo "$file does not exist."
fi

Common parameters (file):

e, -a         #File exist
-f            #File is a regular file
-d            #File is a directory
-s            #File is non-zero size
-h, -L        #File is a symbolic link
-r, -w, -x    #Check file permission
-u            #File’s suid flag is set
-O            #File owner is you
-G            #File group same as yours
!             #reverse

Another example for “file”:

var=`cat file`
if echo $var | grep "search_string"
  then
     echo "search_string found"
  else
     echo "search_string _not_ found"
fi

Another file check examples:

if [ -f /tmp/foo.txt ]
then
    echo "there´s foo.txt!"
    rm /tmp/foo.txt
else
   echo "The file does not exist!"
   echo "Please create a file with the following command:"
   echo "\"touch /tmp/foo.txt\""
fi
Various conditions
 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....
elif
if [ -r somefile ]; then
        content=$(cat somefile)
elif [ -f somefile ]; then
        echo "The file 'somefile' exists but is not readable to the script."
else
        echo "The file 'somefile' does not exist."
fi

Another example:

if [ conditions ]; then
   # Things
elif [ other_conditions ]; then
   # Other things
else
   # In case none of the above occurs
fi

Integer

Example “integer”:

read num;
if [ $num -gt "10" ]
then
echo "$num is greater than 10"
fi

Common parameters (interger):

-eq          #Is equal to
-ne          #Not equal to
-gt          #Greater than
-ge          #Greater or equal
-lt          #Less than
-le          #Less or equal

String

Example “string”:

if [[ $str1 = $str2 ]]
then
echo "They are equal."
fi

Common parameters (string):

=, ==          #Is equal to
=~             #
!=             #Not equal to
>              #Greater than
<              #Less than
-z             #Null string
-n             #Not null string

Note: To check other parameters use “man test”, which uses same syntax!

Array

#Create array, read all "*.pgp" files from working directory and save it into array "array"
array=(*.pgp)
#save array-lengt to variable "arraylength"
arraylength=${#array[@]}
echo $arraylength

#loop runs from index 0 to arraylength
for filename in "${array[@]}"
do
   echo "Filename=$filename"
   gpg --batch --passphrase-file=$PASSPHRASEFILE $filename
done

Access manually array-entry [0]:

echo ${array[0]}

For

#!/bin/sh

#Variable Declaration

startIP=31
endIP=42
ID=1
CAS=10.6.11.

#Restarting tomcat on CAS11 - CAS1x
for (( j = $startIP ; j <= $endIP; j++ ))
        do
        echo "Restarting Tomcat Node $ID"
        echo "Connecting to $CAS$j"
        echo "" | telnet $CAS$j 22 | grep "Escape character is" 2>&1 /dev/null &&  \
        ssh root@$CAS$j '/etc/init.d/tomcat6 restart'
        ID=$[ID+1]
        sleep 30
done


for i in 1 2 3
do
echo $i
done

for i in `find / -name "*.mp3"`
do
rm $i
done

for i in *
do
rm *.mp3
done

for ((  i = 0 ;  i <= 5;  i++  ))
do
   echo "Welcome $i times" 
done
Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

for (( i = 1; i <= 9; i++ )) ### Outer for loop ###
> do
>    for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ###
>    do
>         tot=`expr $i + $j`
>         tmp=`expr $tot % 2`
>         if [ $tmp -eq 0 ]; then
>             echo -e -n "\033[47m "
>         else
>             echo -e -n "\033[40m "
>         fi
>    done
>  echo -e -n "\033[40m" #### set back background colour to black
>  echo "" #### print the new line ###
done

checkerboard:

for (( i = 1; i <= 5; i++ ))      ### Outer for loop ###
do

     for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
     do
           echo -n "$i "
     done

     echo "" #### print the new line ###

done
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
for i in `ls -1`; do echo $i && sleep 1; done
for i in $(ls .pro*); do echo $i;  done

While

Infinite loop:

while true
do
  command
done
#!/bin/sh

while true
do
  echo "test!"
  sleep 5
done

Loop counts until i=11

i=1
n=2

while [ $i -le 10 ]; 
do   
echo "$n * $i = `expr $i \* $n`";   
i=`expr $i + 1`; 
echo "i=$i"
done
#!/bin/bash

CHECK="true"
UIDSTART="3199"

while [ "$CHECK" = "true" ]
do

UIDGREP=`grep $UIDSTART /scripts/uid.txt`

	if [ -z "$UIDGREP"  ]
	then

		echo "user angelegt"
		CHECK="false"

	else

	echo "$UIDSTART ist schon vorhanden"
	UIDSTART=$((UIDSTART-1))

	fi

done
EXTERNAL_PATH=/var/media/ftp/Freetz/external
(
  trap : HUP
  while [ ! -f "$EXTERNAL_PATH"/.external ]; do sleep 3; done
  exec /etc/init.d/rc.external start
) &
#check and set iptables
/sbin/ifconfig -a |/bin/grep ppp0 && PPP_STATUS="0" || PPP_STATUS="1"
echo $PPP_STATUS

while [ $PPP_STATUS == 0 ]
do
        /bin/echo PPP_STATUS=$PPP_STATUS
        /sbin/iptables-restore < /scripts/iptables_restore_ppp0 && /bin/echo "iptables restored" || /bin/echo "iptables not restored"
        /sbin/iptables-save
        /sbin/ifconfig -a |/bin/grep ppp0 && PPP_STATUS="0" || PPP_STATUS="1"
        if [ $PPP_STATUS == 0 ]
        then
        break
        fi
        /bin/sleep 5
done

Check, if file exist and terminate loop if file is in path:

SOCKET="/var/run/mysqld/mysqld.sock"

while [ ! -f $SOCKET ] ;
do
      echo "$SOCKET does not exist."
      sleep 10
done

Function

Example:

#! /bin/sh

start()
{
  echo "start"
}

stop()
{
  echo "stop"
}

t=`ps -ef|grep t[i].sh`
if [ $? -eq 0 ]
then
  start
else
  stop
fi

Example:

#!/bin/sh

###################################################################################################
delete()
{

echo delete application "\"$app1"\"!

#Variables

tomcat=/srv/www/tomcat6/

echo "Removing Deployed Application"

rm -r $tomcat/webapps/$app1

echo "Cleaning Nodes"

rm -r /.cluster/cdsl/?/srv/www/tomcat6/work/Catalina/localhost/$app1
rm -r /.cluster/cdsl/??/srv/www/tomcat6/work/Catalina/localhost/$app1
rm -r /.cluster/cdsl/default/srv/www/tomcat6/work/Catalina/localhost/$app1

rm -r /.cluster/cdsl/??/srv/www/tomcat6/temp/*
rm -r /.cluster/cdsl/?/srv/www/tomcat6/temp/*
rm -r /.cluster/cdsl/default/srv/www/tomcat6/temp/*

echo "done"

}
###################################################################################################


###################################################################################################
start ()
{

app1=0

echo "Please enter Application Name (e.g. applicationname)"

read -p "Application Name : " app1

if [ -z $app1 ];
then

echo "Please enter the application name WITHOUT spaces. Empty strings arent´t allowed as well!";
start

else

delete

fi

}
###################################################################################################

start

Maths

Math addition:

i=$((i+1))              user    0m0.992s
i=$((i++))              user    0m0.964s
((i=i+1))               user    0m0.760s
((i+=1))                user    0m0.700s
((i++))                 user    0m0.644s
((++i))                 user    0m0.556s
let "i=i+1"             user    0m1.116s
let "i+=1"              user    0m1.100s
let "i++"               user    0m1.008s
let i=i+1               user    0m0.952s
let i+=1                user    0m1.040s
let i++                 user    0m0.820s
declare -i i; i=i+1     user    0m0.528s
declare -i i; i+=1      user    0m0.492s
i=0; i=$(expr $i + 1)   user    0m5.464s
shell/if-for-while-function-variable.txt · Last modified: 2024/01/30 13:16 by tmade
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 4.0 International
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki