User Tools

Site Tools


scripts-and-functions

Scripts & Functions


SCRIPTS
true returns a successful (zero) return code
false returns an unsuccessful (non-zero) return code
test <condition> / [ <condition> ] / [[ <condition> ]] evaluates a particular condition and based on its result a successful or unsuccessful return code is provided; to verify the existence of particular files specific options are used with a file name as a parameter - e.g. -e any file, -f regular file, -b block device, -c character device, -d directory, -h symbolic link, -s file with non-zero size, -r file with read permissions, -w file with write permissions, -x executable file, -u file with SUID bit, -g file with SGID bit, -k file with a sticky bit, <file1> -nt <file2> file1 is newer than file2, <file1> -ot <file2> file1 is older than file2; to verify numeric values the following operators are used -eq is equal, -ne is not equal, -lt less than, -le less than or equal, -gt greater than, -ge greater than or equal; to verify strings = is equal, != is not equal, -z <string> the length of string is zero, -n <string> the length of string is non-zero; ! <expression> is used for logical negation of a particular expression; [[ ]] provide more extended expression testing such as: <string> = / == <pattern>, <string> != <pattern>, <string1> < <string2> or <string1> > <string2> (string1 is lexicographically before or after string2) and compound expressions like && to evaluate the second expression if the first is true, || to evaluate the second expression if the first is false and () to group expressions
$ test -f *.txt / [ -f *.txt ]
(return code is 0 if only one file with ".txt" suffix exists)
$ [[ -n $(find . -name "*.txt") ]]
(return code is 0 if at least one file with ".txt" suffix exists)
$ [[ abc == *c ]]
$ [[ a < z ]]
$ [ $PWD = $HOME ] && echo "home" || pwd
$ [[ -n $(rpm -qa | egrep "^sudo") && $(stat -c %s /etc/sudoers) -gt 0 ]] && echo "Sudo is used." || echo "Sudo is not used."
# duid=$(awk -F ":" '{print $3}' /etc/passwd | sort | uniq -d); [[ -z "$duid" ]] && echo "NONE" || echo "$duid"
(prints duplicate UID in the system)
# pp=$(awk -F ":" '{if (length($2) > 2) print $1}' /etc/passwd); [[ -z "$pp" ]] && echo "NONE" || echo "$pp" | tr " " "\n"
(prints users whose passwords are stored in /etc/passwd)
if <condition=true>; then <action>; (elif <condition2=true>; then <action2>;) (else <action3>); fi if specifies a condition, if it is true, then then specifies a required action, otherwise else specifies an alternative action, additional conditions can be specified by elif, the end of all conditions is closed with fi
$ if test -f *.txt / [ -f *.txt ]; then echo "file exists"; fi
$ if [ "$(whoami)" != 'root' ]; then exit; else echo "hello"; fi
$ if [ $? -ne 0 ]; then echo $?; fi
(return code is 0 if the last command finished unsuccessfully)
# np=$(awk -F ":" '{if (length($2) > 2 && $2 !~ /^(!!)?(\$[1256]\$)/) print $1}' /etc/shadow); if [[ -z "$np" ]]; then echo "All passwords are encrypted."; else { echo "Password may not be encrypted or is incorrect for user:"; echo "$np" | tr " " "\n";}; fi
(prints users with not encrypted or incorrect passwords)
case <string> in <pattern>(|<pattern>) <list>;; esac executes a command provided the string matches the pattern; the string represents any variable, pattern "*" specifies an action if both the values do not match (similar to command "else"), the list of patterns is closed with ")" and the group of commands end up with ";;"
#!/bin/bash
# The script creates or deletes a file according to the action.
echo -n 'Enter an action and file name: '
read ACTION FILE
case $ACTION in
     remove|delete)     rm $FILE;;
     make|create)       touch $FILE
                                           chmod 777 $FILE;;
     *)                 echo 'Unknown operation';;
esac
read <word> reads the line from STDIN and splits it into words which are then assigned to particular variables for further processing, -n <number_of_characters> reads a particular number of characters only, -r suppresses a special meaning of "\" character, -s does not display particular characters
#!/bin/bash
# The script asks the user to enter a user name and password
# and confirms it.
echo -n "Username: "; read username
echo -n "Password: "; read -s password
echo " "
echo "Password for $username submitted."

$ cat test | { read a; read b; read c; echo "$a/$b/$c";}
while <list1>; do <list2>; done executes repeatedly "list2" until "list1" returns a successful return code
#!/bin/bash
# The script opens four terminal screens.
I=0
while [ $i -lt 4 ]; do xterm &
     i=$[$i+1]; done

#!/bin/bash
# The script creates a file every five minutes.
while true; do
     touch pic-`date|awk '{print $2,$3,$4,$6}'|sed 's/ /_/g'`.jpg
     sleep 300; done
until <list1>; do <list2>; done executes repeatedly "list2" until "list1" returns an unsuccessful return code
#!/bin/bash
# The script prints numbers 0 - 99.
a=-1
until [ $a -eq 99 ]; do
     a=$(expr $a + 1)
     echo $a; done

#!/bin/bash
# The script copies files from home to web directory where it
# creates a new directory every hour and in case it is more
# than 90% full it removes directories older than thirty days.
while true; do
     DISKFUL=$(df -h $WEBDIR | grep -v File | \
     awk '{print $5 }' | cut -d "%" -f1 -)

     until [ $DISKFUL -ge "90" ]; do
          WEBDIR=/var/www/webcam
          DATE=`date +%Y%m%d`
          HOUR=`date +%H`
          mkdir $WEBDIR/"$DATE"

               while [ $HOUR -ne "00" ]; do
               PICDIR=/home/user/pics
               DESTDIR=$WEBDIR/"$DATE"/"$HOUR"
               mkdir "$DESTDIR"
               cp $PICDIR/*.jpg "$DESTDIR"/
               sleep 3600
               HOUR=`date +%H`; done

     DISKFULL=$(df -h $WEBDIR | grep -v File | \
     awk '{ print $5 }' | cut -d "%" -f1 -)
     done

TOREMOVE=$(find $WEBDIR -type d -mtime +30)
     for i in $TOREMOVE; do
     rm -rf "$i"; done
done
for <variable> (in <string>); do <list>; done assigns a variable one by one the value of all parameters of the script or a particular string and executes a list of commands
#!/bin/bash
# The script creates users specified in "users" file
# in the working directory, adds them to "admins" group
# and assigns "password" as their password.
for user in $(cat users); do
     useradd -g admins $user
     echo password | passwd --stdin $user
done

#!/bin/bash
# The script prints the contents of the working directory.
for x in $(ls -F)
do
     echo "Directory `pwd` contains file/directory: $x"
done

#!/bin/bash
# The script counts the number of items in the working directory.
POC=0
for name in *
     do
          POC=$(($POC+1))
     done
echo "Directory `pwd` contains $POC items."

#!/bin/bash
# The script converts the format of all .tif files to .jpg.
for pic in *.tif; do
     convert "$pic" "$(echo "$pic" | sed 's/\.tif/.jpg/')"
done

#!/bin/bash
# The script checks which of the particular processes are running,
# prints their names and the number of lines they occupy and
# finally prints all running processes and the total number of
# lines.
services="http pmon lsnr sap"
for service in $services
     do running_processes="$(ps -ef | grep $service | grep -v grep)"
          if [ -n "$running_processes" ]
               then echo
               echo $service:
               echo
               echo "$running_processes"
               echo
               echo "lines: $(echo "$running_processes" | wc -l)"
               echo
               echo "=========="
          fi
     done
echo
echo "summary:"
echo
ps -ef
echo
echo "lines: $(ps -ef | wc -l)"

#!/bin/bash
# The script connects to all the servers whose IP addresses
# are specified in "servers" file, remotely executes commands
# "hostname" and "uname -a" and displays the result in STDOUT.
# Valid rsa / dsa authentication keys for ssh are mandatory.
for a in $(cat servers); do
ssh $a 'hostname; uname -a'; done
break (<n>) exits from within a loop, n specifies the number of loops
#!/bin/bash
# The script exits if the value of the variable is equal to 3.
for myloop in 1 2 3 4 5; do
     echo "$myloop"
     if [ "$myloop" -eq 3 ]; then
     break # This line will break out of the loop; fi
done
continue (<n>) repeates within a loop, n specifies the number of loops
#!/bin/bash
# The script allows only small letters in file names.
LIST="$(ls)"
for name in "$LIST"; do
     if [[ "$name" != *[[:upper:]]* ]]; then
     continue; fi

ORIG="$name"
NEW=$(echo $name | tr 'A-Z' 'a-z')
mv "$ORIG" "$NEW"
echo "new name for $ORIG is $NEW"
done
exit (<n>) exits a script with the specified return code, if it is omitted, the return status is that of the last command executed in the script body


FUNCTIONS
function <function_name> { <list>;} / <function_name> () { <list>;} defines a function whose contents is enclosed in braces; the function is used for frequent execution of particular commands and it is launched by its name in the current shell returning a status code of the last executed command provided there is no other specified by "return" command; a local variable (which is inherited also into subfunctions) can be defined by "local" command inside the function, if a global variable of the same name exists, it is suppressed in the function; a function can be used permanently (in future shell executions) if it is specified in .bashrc; information about forwarded arguments to scripts or functions are saved in special variables ("$#" total number of arguments, "$<n>" particular argument in the order in a range of 1 - 9, "${<n>}" any argument in the order, "$*" all arguments)
# Function "test" creates a file which name is specified
# by the argument and sets particular permissions for it.
# If a file of the given name already exists or the name contains
# just space or is missing an error message is displayed.

$ function test
> {
> if ! [ -e $* || $* = '' ]; then
>     touch $*; chmod 755 $*
> else
>     echo "Error"
> fi
> echo "Number of arguments: $#"
> echo "All arguments: $*"
> echo "Fifth argument: $5"
> }

# Function "user" checks if a specified user given by the argument
# exists in the system, if so it prints related detailed
# information.

$ user ()
> {
> if [ $(grep -ic ^$1 /etc/passwd) -eq 0 ]; then
>     echo "User $1 does not exist."
> else
>     echo "User $1 exists." && finger $1
> fi
> }

# Function "poc" computes a percentage value of the second numeric
# argument from the first one, provided the first argument
# represents value 100%.

$ poc () {
> local x=$1 y=$2
> echo "$x = 100%, $y = x%"
> echo "$y = $[$(( 100 * $y )) / $x]% z $x"
> }
return (<n>) exits a function with the specified return code, if it is omitted, the return status is that of the last command executed in the function body
Last modified: 2017/02/14 22:23 by Miroslav Bernát

visits: