Script Course

From rbachwiki
Jump to navigation Jump to search

File Operators Tests

Escape Sequence
Test Statements
Commands used with pipe
  • -d File True if file is a directory
  • -e File True if file exists
  • -f File True if file exists and is a regular file
  • -r File True if file is readable by you
  • -s File True if file exist and is not empty
  • -w File True if the file is writable by you
  • -x File True if the file is executable by you
  • -z String True if string is empty
  • -n String true if string is not empty

Syntax

[condition to test for]

Example

[ -e /etc/passwd ]
-e True if file exists

Exit Status return codes

  • Every command returns an exit status
  • range from 0 - 255
  • 0 = success
  • Other than 0 = error condition
  • use for error checking

$? Contains the return code of the previously executed command

ls /not/here
echo "$?"

-

HOST = "google.com"
ping -c 1 $HOST
if [ "$?" -eq "0" ]
then 
echo "$HOST reachable."
else
echo "$HOST unreachable"
fi

' And and || or

  • && = And : if first fails the other won't be executed
mkdir /tmp/bak && cp test.txt /tmp/bak/
  • || OR - if one fails the other will be processed
cp test.txt /tmp/bak || cp test.txt /tmp

Redirection

redirect to non error using status code 1 to filename goodoutput

ls /etc 1>goodoutput
ls /etc > 2>badoutput

Redirect both at the same time

ls /etc >goodoutput 2>badoutput

tee command, which takes information from Standard Input and sends that information to a file, as well as to Standard Output.

cat prologue|tr a A|sort|pr –d|tee newfile|less

Chaining multiple commands

cp test.txt /temp; cp test.text /tmp

Bash Functions

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

Call Script

hello Jason Dan Ryan

Those three names will be processed individually

SED Command

The sed command is typically used to search for a certain string of text, and replaces that text string with another text string using the syntax s/search/replace/. For example, the following output demonstrates how sed can be used to search for the string “the” and replace it with the string “THE”

cat filename.text | sed /s/the/THE

Notice from the preceding output that sed only searched for and replaced the first occur- rence of the string “the” in each line. To have sed globally replace all occurrences of the string “the” in each line, simply append a g to the search-and-replace expression:

cat prologue | sed s/the/THE/g

Bash menu- Home