Variabile: Atribuire - Greeting "Hello" Echo $greeting

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

 ls –l file -> view permissions on a file

Permission denied – change permissions : chmod u+x file (executable only for the user)

Chmod a+x file (executable for everyone)

Data - echo $(date): >>file

PATH = “$PATH:~/bin”

(Shebang)Bash scripts: #!/bin/bash

Other systems than Linux or Mac OS: #!/usr/bin/env bash

Variabile : atribuire -> greeting=”hello” ; echo $greeting

 filename=”somefile.txt”; touch $filename; ls $filename


 to get the value : Prefix with $ : echo $x

important!

 Use $HOME instead of ~


 “set-x” –enable and “set+x” -disable

Documentation: “help read” or “man builtins”

IF-THEN-ELSE : if testcode; then successcode; else failcode; fi //help if


If testcode; then
#Code here gets executed
#When tescode succeeds
Else
#Code here gets executed
# When testcode fails
Fi

Arithmetic tests : (integers only) [[ arg1 OP arg2 ]]


OP ->
 -eq:equality
 -ne: not equal
 -lt: less then
 -gt: greater then
 !!! don’t use =,<,> for numbers!

Special variables: $# contains number of script arguments

$? Contains exit status for last command

The length of the string in a variable: ${#var}

And, Or, Not

 Use ! to negate a test: [[ ! –e $file]] – a file doesn’t exist


 Use && for “and”: [[ $# -eq 1 && $1 = “foo”]]
 Use || for “or”: [[ $a || $b]] – true if a or b contains a value (or both)

Printf –v greeting “hello”: -v -> will send output to a variable


//http://wiki.bash-hackers.org/commands/builtin/printf
Read – input into a variable “read x”
-n -> stop when new line; -N –stop when have the number of variables
-s will suppress output (useful for passwords)
-r disallows escape sequences, line continuation
 Read a b / hi there; echo $a –hi, echo $b – there

Standard Streams

 0: Standard Input (stdin) -> /dev/stdin


 1: Standard Output (stdout) -> /dev/stdout
 2: Standard Error (stderr) -> /dev/stderr
 /dev/null discards all data sent to it

Input redirection: < grep milk < shoppingnotes.txt

Output redirection: > ls>listing.txt ( Will overwrite existing files!)

 >> appends to the end of a file

Pipes: ls | grep x

Redirect: cmd < inputfile > outputfile // >outputfile cmd < inputfile
Control flow

1. While // test returns true


While test; do
;; code to be repeated
Done
2. Until // test returns false
Until test; do
;; code to be repeated
Done
3. For // assign each word in WORDS to var in turn
a) for VAR in WORDS; do
;; code to be repeated
Done
b) for (( INIT; TEST; UPDATE )); do
;; loop code
done

4. CASE
case WORD in
PATTERN1)
Code for pattern1;;
PATTERN2)
Code for pattern2);;
….
PATTERNn)
Code for pattern n);;
esac
// multiple patterns separated by |
Exemple:
Group commands
1. {} – a single statement {cm1; cmd2; cmd3}
2. || and &&
a) && - will execute next statement only if previous one succeeded
b) || - will execute next statement only if previous one failed

****

 Get a random number < 100 : target=$(($RANDOM % 100))


 Verify if the first argument is a number: if [[ $1 =~ ^[0-9]+$ ]];; [[ ${OPTARG} =~ ^[0-9]+$ ]]
 $# - number of arguments : ${#var}: length of $var
 $* and $@ - give all arguments
 $* = “arg1 arg2 arg3….argn”
 $@ = “arg1” “arg2” “arg3”….
 Link: ln -s ./scriptname sn
 Clean up: rm “$tempfile” / exit 0
 Functions and redirection: fun(){…} >&2 (stderr)
 ^ ->matches start of string
 $ -> matches end of string
 + -> matches the token before it for one or more times: [0-9]+ will match 1 or more digits
 *-> matches the token before it for any number of times: [a-z]* will match any lowercase text or
nothing at all
 ? -> matches the token before it 0 or 1 times: [0-9]? Will match a single digit or nothing at all
 =~ -> does regular expression matching
 ${BASH_REMATCH[1]} – 020->20
 Ask user for input: read –p “Your note:” note
 Count -> Permission denied => bash –x count
 $(basename $0) = script_name.sh / $0 = /path/to/scropt_name.sh

Variables

 Integer variables: declare –(+)i num : EX: declare –i p; p=”4+5”; echo $p => 9
 Arithmetic Expressions: let command: let n=100/2
((++x))
 Read-only variables: declare –r constant=”some value”
 Exporting variables: export var=”value” / declare –x var=”value”

Arrays – can hold multiple values: declare –a x // more info: http://goo.gl/g6xtca

 Storing a value: x[0]=”some”; x[1]=”word”


 Retrieving a value: ${x[0]}: some; ${x[@]} or${x[*] } retrieve all values
 Initializing an arry: ar=(1 2 3 a b c)
 Count the number of elements in $array: echo ${#array[@]}
 The indices in $array: echo ${!array[@]}
 Exemple: ar=(this is an array); declare –p ar; echo${ar[2]} ->an

Special Variables

1. Positional Parameters: hold the n-th command line argument: $1, $2, etc.; ${10}
2. $0: holds name of the script as it was called
3. $@ ~ $*: All (Equivalent to $1 $2 $3…$N)
4. $#: Holds the number of arguments passed to the script
5. Shift: removes the first argument: $2 -> $1; $3 -> $2
 Shift 3 – removes the first three arguments
6. Getopts: getopts optstring name, where optstring=a list of expected options
 It will place the next option into $name
 Handling errors: - unknown option: “?” in option variable NAME; actual option in
OPTARG
- Missing option argument: “:” in option variable NAME; actual
option in OPTARG

Functions

 Define your own command: function name() {…}

Removing a pattern
 Removing part of a string:
 ${var#pattern} – Removes shortest match from begin of string
 ${var##pattern} – Removes longest match from begin of string
 ${var%pattern} – Removes shortest match from end of string
 ${var%%pattern} – Removes longest match from end of string

 Search and Replace:


 ${var/pattern/string} – substitute fisrt match with string. Exemple: i=”mytxt.txt”; echo $
{i/txt/jpg} -> myjpg.txt; echo${i/%txt/jpg}-> mytxt.jpg
 ${var//pattern/string} – substitute all matches with string

 Anchor your pattern


 ${var/#pattern/string} – matches beginning of the string
 ${var/%pattern/string} – matches end of the string

Default values // more info : http://goo.gl/xRHo3u


 Default value:
 ${var:-value} – will evaluate to “value” if var is empty or unset
 ${var-value} – similar, but only if var is unset
 Assign a default value:
 ${var:=value} – if var is empty or unset, this evaluates to “value” and assigns it to var
 ${var=value} – similar, but only in var is unset

End of options: id denoted by –

Many ways to run your script

 Running code from a file


 Using hash-bang and running it as a command + executable permission
 When it doesn’t have a hash-bang: bash myscript, no permissions necessary, bash –x
myscrip
 Import code in the current shell process: source myscript; .myscript

 Background and nohup


 Put a command in the background with &: myscript & = put myscript in background
and it will be disconnected from the interactive session
 Long-running scripts: (remote connection, logout but you don’t want your script to exit)
nohup myscript & : Exemple: nohup ./stillhere > log; tail log (exit your terminal)
 Run your script with a lower priority: nice myscript / nohup nice myscript &
 Redirecting with exec
 Redirect I/O for the whole script: useful for (logging): exec >logfile 2 >errorlog
 Running your script another time
 At : will execute your script at a specific time: at –f myscript noon tomorrow
 Cron: will execute your script according to a schedule:
o Mac OS – launchd
o Ubuntu – Upstart

Set and shopt

1. Set // more info->help


-x -> prints each command with its arguments as it is executed
-u -> gives an error when using an uninitialized variable and exits script
-n -> read commands but do not execute
-v -> print each command as it is read
-e -> exits script whenever a command fails (but not with if, while, until, ||, &&)

2. Shopt
-can set many options with –s, unset with –u
o Shopt –s nocaseglob : ignore case with pathname expansion
o Shopt –s extglob: enable extended pattern matching
o Shopt –s dotglob: include hidden files with pathname expansion

RED HAT

 ~=$HOME
 ./ = Current Directory
INPUT : READ COMMAND

Read –p “Enter first number: ” value1


Read –p “Enter first number: ” value2
Let answer=$value1*$value2
Echo “$answer”

Press any key: read –n1 –p “Press any key when you’re ready to see the answer”
“Silent mode” (don’t see the key pressed on the screen): read –sn1 –p “Press any key when
you’re ready to see the answer”
**** the key pressed that isn’t show on the screen is stored in default variable : echo $REPLY

FILE TEST OPERATORS

 -e : File exists
 -b : Block device files
 -c : Char device files
 -f : Regular files
 -r : Read access
 -w : Write access
 -x : Execute permission
 -s : Same as –x

WHILE/UNTIL

 While – Loop while true. Exit loop when false


 Until – Loop while false. Exit loop when true

BREAK/CONTINUE

 BREAK –Code after Break command is ignored. (next command – after done)
 Continue - Code after Break command is ignored. (next command – back to the loop (while))

Building our first simple menu


Exemple
options="Sunderland Newcastle"
select choice in $options ; do
echo "REPLY variable is $REPLY"
echo "choice variable is $choice"
done
//Reply variable is 1 // choice variable is sunderland
Functions
Syntax:
Educate_user()
{
<<code>>
}

Scheduling a Script

 Recurring Tasks – Cron, Anacron


 One-off Tasks – at, batch

Cron – [Misses jobs if the system is down] - Minute, Hour, Day of Month, Month, Day of Week

Anacron – [Doesn’t miss jobs if the system is down] – Can only run jobs once per day!!!

Exist Statuses

Exist Status = 0 / Exist Status !=0

exit 2 => Exit code 2 = not root

exit 3 => Exit code 3 = no arguments specified

exit 4 => Exit code 4 = not enough disk space

xtrace

set –x=> xtrace on

set +x =>xtrace off

You might also like