Difference between revisions of "Shell Scripting"

From rbachwiki
Jump to navigation Jump to search
 
Line 161: Line 161:


  #!/bin/bash
  #!/bin/bash
cd /var/www/bash
cd /var/www/bash
   # there's a space after the "if", space afer ! then a space after "[", space before "]"
   # there's a space after the "if", space afer ! then a space after "[", space before "]"
  if [ ! -d  /var/www/bash/text/ ]
  if [ ! -d  /var/www/bash/text/ ]

Latest revision as of 14:47, 30 June 2022

Shell Scripting

Scripts must be chmod 755 so they can execute

(add to the top of the shell script so it can use the bash shell to interpret the script, you can also add python or other shell programs)

#!/bin/bash 

Positional Parameters: $0 ... $9 $@ to access all 0-9 // like in a loop

Exit Status return Codes: Range from 0 to 255: 0 = success: Other than 0 = error condition: use man or info to find meanign of exit status

&bull, $? contains the return code of the previously executed command

ls /not/here
   echo "$?"

Another Code example

 HOST="google.com"
 ping -c 1 $HOST # -c 1 means it will send 1 ping
 if["$?" -eg "0"]
   then
      echo "$HOST reachable"
     else
       "$HOST unreachable"
     fi
&& and ||

the second statement only executes if the first one was successful

mkdir /tmp/bak && cp test.txt /tmp/bak/

the second statement will execute only if the first one fails

cp test.txt /tmp/bak/ || cp test.txt /tmp

chain multiple commands together using a ; (semicolon)

cp test.txt /tmp/ ; cp test.txt /bak


File Operators (test)

-d FILE -true if is a directory
-e FILE True if file exists
-f FILE True if file exist and is a regular file
-r FILE True if file is readable by you
-s FILE True if file exists and is not empty
-w FILE True if file is writable by you
-x FILE True if file is executable by you
-z FILE True if string is empty
-n FILE True if string is not empty
String1=String2 true if strings are equal
String1 != string2 True if the strings are not equal
arg1 -eq arg2 equal
arg1 -ne arg2 not equal
arg1 -lt arg2 less than
arg1 -le arg2 less than or equal to
arg1 -gt arg2 greater than
arg1 -ge arg2 greater than or equal to
read -p "Prompt to dispaly" VarableName accepting user input

for loop to rename all jpg files with the date

  #!/bin/bash
  PICTURES=$(ls *.jpg)
  DATE=$ (date +%F)

  for PICTURES IN $PICTURES
      do
          echo "Renaming ${PICTURE} to ${DATE} - ${PICTURE}"
          mv $[PICTUE} ${DATE}-${PICTURE}
  done

  // Output
  renaming bear.jpg to 2015-03-06-bear.jpg

Adding exit commands to scripts

    #!/bin/bash
      HOST="google.com"
      ping -c 1 $HOST
      IF [ "$?" -ne"0" ]
      then
          echo "$HOST unrechale"
          exit 1
      fi
      exit 0

Creating a Function

function function-name() {# code goes here}

Calling a Function

function hello() {
   echo "hello:
   }

hello (you don't need the () just call the name of the function)

Positional Parameters and passing info to a function

#!/bin/bash
 function hello(){
     echo "hello $1"
 }


hello robert # robert is passed to the function hello

#output is hello Robert

Outputting multiple calls to a function

#!/bin/bash
     function hello() {
     for NAME in $@
     do
         echo "Hello $NAME"
     done
 }
hello robert bob dan

Output

hello robert bob dan

Using Wildcards

* -matches zero or more characters
*.txt
a*
a*.txt
? - matches exactly one character
?.txt
a?
a?.txt
[] character class - matches any of the characters included between the brackets. Matches exactly one character.
[aeiou]* exampld: ls -la [abge]*
ca[nt] matches:(it will match either the n or the t)
can, cat, candy, catch
[!] Matches any characters NOT included between the brackets. Matches exactly one character.
[!aeiou]* would match below bacause it does not start with any of those letters
baseball, cricket
Select a range
[a-g]* matches files that start with a,b,c,d,e,f,g
[3-6]* matches all files start with 3,4,5,6
Using predefined Character Classes
[[:alpha:]]
[[:alnum:]]
[[:digit:]]
[[:lower:]]
[[:upper:]]
[[:space:]]
#!/bin/bash
cd /var/www/bash
 # there's a space after the "if", space afer ! then a space after "[", space before "]"
if [ ! -d  /var/www/bash/text/ ]
then
    mkdir /var/www/bash/text
fi
for FILE in *.txt
do
    echo "Copying $FILE"
    cp $FILE /var/www/bash/text
done

Case Statements

Simple Backup bash shell script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig
 
Your backup script and variables:
#!/bin/bash
 OF=myhome_directory_$(date +%Y%m%d).tar.gz
 tar -czf $OF /home/linuxconfig 
 
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 


Back To Top- Home - Category