SlideShare a Scribd company logo
Bash Scripting

       Prepared by Ahmed Magdy Ezzeldin
File System

●   / is not allowed in a file name
●   file extensions are not important
●   File and folder names are case sensitive
●   Names containing spaces are escaped by  or ""
●   Hidden files start with .
●   Current directory alias . and parent directory alias ..
●   ls, ls -a, ls -l, cp, mv, rm, rm -rdf, ln, ln -sf
Variable and Strings

●   Strings are enclosed in “” '' or just written with spaces escaped
    by 
    VAR=”How are you”
    VAR='How are you'
    VAR=HOW are you
●   Variables
    $VAR
    ${VAR} # e.g. ${FILE}.txt
    echo “my name is $NAME”
    echo “my name is “$NAME
    read VAR
    read VAR1 VAR2
Math

●   echo $((1+1))
●   echo $[1+1]
●   echo `expr 1 + 1`
●   A=$((B*C))
●   let A+=1
●   echo "3.4+7/8-(5.94*3.14)" | bc
File Ownership and Permissions

●   Group and Ownership
    chown, chgrp, ls -l
    chown user:group file
    sudo chown

●   Permissions of files and directories
    chmod 755 file
    chmod +x file
    chmod -x file
                   (r)ead     (w)rite      e(x)ecute

                     4           2            1
Users, su, sudo

●   su, sudo, visudo, /etc/sudoers, su user
●   sudo bash
●   /etc/passwd
●   ~/
Processes and Subshells

●   ps, pgrep, top, jobs, fg, &, kill, signals
●   Sub-shells from :
    ●   Loops
    ●   $()
    ●   Back ticks ``
    ●   bash command
●   /proc
●   fuser
Loops

●   While loop
    while read VAR; do echo $VAR; done
●   For each loop
    for VAR in {1..5}; do echo $VAR; done
    for VAR in 1 2 3 4 5; do echo $VAR; done
    for VAR in {0..10..2}; do echo $VAR; done
    for VAR in $(seq 0 2 10); do echo $VAR; done
●   For loop with counter
    for (( i=0; i<=10; i+=2 )); do echo $i; done
if and switch case

●   If then, else, elif, fi
    if [ -d $F ]; then
        rm -rdf $F
    elif [ -f $F ]; then
        rm $F
    else
        echo “Unknown file type”
    fi
●   case, esac
    while read l; do
     case $l in
      1) echo "One";;
      2) echo "Two";;
      3) echo "Three";;
      *) echo "Invalid"; break;;
     esac
    done
I/O Redirection

●   >, >>, <, &>, 2&>, 2>, |
    echo “error” 1>&2 # redirect std_output to std_err
    some_error_producing_command 2>&1
    some_command &>> log_file_errors_and_output
    some_command >> log_file_output_only
    some_command 2>> log_file_errors_only
    command | filter_command
    command < file
    command > file # truncates and writes into file
    command1 2>&1 | command2
    command1 |& command2
●   Mute by redirecting to /dev/null file
Named Pipes and Network and Signal Processing
●   Network
      exec 9<>/dev/tcp/google.com/80
      echo -e "GET / HTTP/1.0nn" >&9
      while read line <&9; do echo $line; done
●   Named Pipes
      mkfifo pipe
      while read l; do echo $l; done < pipe
      echo “hi” > pipe # on another terminal window
●   Signal Processing
      #!/bin/bash
      function handle_signal () {
         echo "Hi man I got the signal"
      }
      trap "handle_signal; exit" SIGINT
      sleep 100
Cool Stuff and GUI
●   Install these: libnotify-bin, zenity, festival
●   date '+%l oclock' | festival –tts
●   zenity --list --hide-header --text="Are you coming today?" --checklist --column
    "" --column "" FALSE "Yes" FALSE "No" FALSE "May be"
●   zenity --calendar --date-format="%Y/%m/%d"
●   zenity --text="Select Hour" --title="Select Hour" --scale --min-value=0 --max-
    value=24 --value=17
●   zenity --text="Select Minutes" --title="Select Minutes" --scale --min-value=0
    --max-value=59 --value=0
●   zenity --info --text="Did you know this info"
●   zenity --error --text="There is an error"
●   zenity --entry | festival --tts
●   zenity --file-selection
●   <progres command> | zenity --progress --auto-close
●   notify-send -t 10 "hi man" "details"
Launchers

  ● When you drag a file or folder onto a launcher
  it is sent as $1 to the launcher script
Example Codes

●   Bluetooth Obex-push
    NEW_FILE_NAME=`echo $1 | awk -vFS="/" '{print $NF;}'`
    ussp-push 00:22:65:89:22:E6@9 "$1" "$NEW_FILE_NAME"
●   Close the computer when your browser finishes downloading
    your_file
    while true; do sleep 5; if [ -z "`fuser ~/your_file`" ]; then break;
    fi; done; sudo init 0
●   Tell me the time whenever I lock my screen or unlock it
●   Simple spider using curl and wget
●   Log your time easily and report to a Redmine service
●   Think of more ...
Thank you
References


    http://www.linuxcommand.org/lts0040.php

    http://www.cyberciti.biz/faq/bash-for-loop/

       http://linuxcommand.org/wss0160.php

  http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-10.html


 http://wiki.bash-hackers.org/syntax/redirection

  http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html

More Related Content

PPTX
Process monitoring in UNIX shell scripting
PPTX
Cis 216 – shell scripting
PDF
Tomáš Čorej - OpenSSH
PDF
Redis & ZeroMQ: How to scale your application
PDF
PDF
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
PDF
ZeroMQ Is The Answer
PPTX
Unix shell scripting
Process monitoring in UNIX shell scripting
Cis 216 – shell scripting
Tomáš Čorej - OpenSSH
Redis & ZeroMQ: How to scale your application
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
ZeroMQ Is The Answer
Unix shell scripting

What's hot (20)

PPTX
Comets notes
PDF
React PHP: the NodeJS challenger
ODP
The promise of asynchronous PHP
DOC
How to send files to remote server via ssh in php
PDF
Unix cheatsheet
PDF
ZeroMQ Is The Answer: DPC 11 Version
PDF
How to stand on the shoulders of giants
PDF
ZeroMQ: Messaging Made Simple
KEY
Clojure + MongoDB on Heroku
ZIP
Web Apps in Perl - HTTP 101
PDF
Any event intro
PDF
Créer une base NoSQL en 1 heure
PDF
Parsing JSON with a single regex
PDF
Shell Script
PDF
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
PDF
Coming Out Of Your Shell - A Comparison of *Nix Shells
PDF
Devinsampa nginx-scripting
PDF
Puppet Camp 2012
ODP
Perl - laziness, impatience, hubris, and one liners
PDF
Laporan setting dns
Comets notes
React PHP: the NodeJS challenger
The promise of asynchronous PHP
How to send files to remote server via ssh in php
Unix cheatsheet
ZeroMQ Is The Answer: DPC 11 Version
How to stand on the shoulders of giants
ZeroMQ: Messaging Made Simple
Clojure + MongoDB on Heroku
Web Apps in Perl - HTTP 101
Any event intro
Créer une base NoSQL en 1 heure
Parsing JSON with a single regex
Shell Script
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Coming Out Of Your Shell - A Comparison of *Nix Shells
Devinsampa nginx-scripting
Puppet Camp 2012
Perl - laziness, impatience, hubris, and one liners
Laporan setting dns
Ad

Similar to Bash Scripting Workshop (20)

PDF
One-Liners to Rule Them All
ODP
Unix tips and tricks
PDF
Shell scripting
PPTX
Perl basics for Pentesters
PDF
Mac OSX Terminal 101
PPT
Shell Scripts
PDF
IO Streams, Files and Directories
PPTX
Linux And perl
PPT
101 3.4 use streams, pipes and redirects
PDF
Python build your security tools.pdf
PDF
Unit 10 investigating and managing
PPT
Unix shell scripting basics
PPT
Unix Shell Scripting Basics
DOCX
Really useful linux commands
PDF
Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...
PDF
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
PDF
A journey through the years of UNIX and Linux service management
TXT
Logrotate sh
PPT
Shell Scripting
PDF
Ansible tips & tricks
One-Liners to Rule Them All
Unix tips and tricks
Shell scripting
Perl basics for Pentesters
Mac OSX Terminal 101
Shell Scripts
IO Streams, Files and Directories
Linux And perl
101 3.4 use streams, pipes and redirects
Python build your security tools.pdf
Unit 10 investigating and managing
Unix shell scripting basics
Unix Shell Scripting Basics
Really useful linux commands
Phishing for Root (How I Got Access to Root on Your Computer With 8 Seconds o...
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
A journey through the years of UNIX and Linux service management
Logrotate sh
Shell Scripting
Ansible tips & tricks
Ad

More from Ahmed Magdy Ezzeldin, MSc. (12)

PDF
Distributed RDBMS: Challenges, Solutions & Trade-offs
PDF
Win any Interview like a Boss
PDF
Answer Selection and Validation for Arabic Questions
PDF
Arabic Question Answering: Challenges, Tasks, Approaches, Test-sets, Tools, A...
PDF
A survey of fault prediction using machine learning algorithms
PDF
GATE : General Architecture for Text Engineering
PDF
Networks and Natural Language Processing
PDF
Distributed Coordination-Based Systems
PDF
Distributed Systems Naming
PDF
Cyclcone a safe dialect of C
PPT
Objective C Memory Management
PPT
Object Role Modeling
Distributed RDBMS: Challenges, Solutions & Trade-offs
Win any Interview like a Boss
Answer Selection and Validation for Arabic Questions
Arabic Question Answering: Challenges, Tasks, Approaches, Test-sets, Tools, A...
A survey of fault prediction using machine learning algorithms
GATE : General Architecture for Text Engineering
Networks and Natural Language Processing
Distributed Coordination-Based Systems
Distributed Systems Naming
Cyclcone a safe dialect of C
Objective C Memory Management
Object Role Modeling

Recently uploaded (20)

PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Transforming Manufacturing operations through Intelligent Integrations
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Spectral efficient network and resource selection model in 5G networks
Chapter 3 Spatial Domain Image Processing.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Sensors and Actuators in IoT Systems using pdf
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation

Bash Scripting Workshop

  • 1. Bash Scripting Prepared by Ahmed Magdy Ezzeldin
  • 2. File System ● / is not allowed in a file name ● file extensions are not important ● File and folder names are case sensitive ● Names containing spaces are escaped by or "" ● Hidden files start with . ● Current directory alias . and parent directory alias .. ● ls, ls -a, ls -l, cp, mv, rm, rm -rdf, ln, ln -sf
  • 3. Variable and Strings ● Strings are enclosed in “” '' or just written with spaces escaped by VAR=”How are you” VAR='How are you' VAR=HOW are you ● Variables $VAR ${VAR} # e.g. ${FILE}.txt echo “my name is $NAME” echo “my name is “$NAME read VAR read VAR1 VAR2
  • 4. Math ● echo $((1+1)) ● echo $[1+1] ● echo `expr 1 + 1` ● A=$((B*C)) ● let A+=1 ● echo "3.4+7/8-(5.94*3.14)" | bc
  • 5. File Ownership and Permissions ● Group and Ownership chown, chgrp, ls -l chown user:group file sudo chown ● Permissions of files and directories chmod 755 file chmod +x file chmod -x file (r)ead (w)rite e(x)ecute 4 2 1
  • 6. Users, su, sudo ● su, sudo, visudo, /etc/sudoers, su user ● sudo bash ● /etc/passwd ● ~/
  • 7. Processes and Subshells ● ps, pgrep, top, jobs, fg, &, kill, signals ● Sub-shells from : ● Loops ● $() ● Back ticks `` ● bash command ● /proc ● fuser
  • 8. Loops ● While loop while read VAR; do echo $VAR; done ● For each loop for VAR in {1..5}; do echo $VAR; done for VAR in 1 2 3 4 5; do echo $VAR; done for VAR in {0..10..2}; do echo $VAR; done for VAR in $(seq 0 2 10); do echo $VAR; done ● For loop with counter for (( i=0; i<=10; i+=2 )); do echo $i; done
  • 9. if and switch case ● If then, else, elif, fi if [ -d $F ]; then rm -rdf $F elif [ -f $F ]; then rm $F else echo “Unknown file type” fi ● case, esac while read l; do case $l in 1) echo "One";; 2) echo "Two";; 3) echo "Three";; *) echo "Invalid"; break;; esac done
  • 10. I/O Redirection ● >, >>, <, &>, 2&>, 2>, | echo “error” 1>&2 # redirect std_output to std_err some_error_producing_command 2>&1 some_command &>> log_file_errors_and_output some_command >> log_file_output_only some_command 2>> log_file_errors_only command | filter_command command < file command > file # truncates and writes into file command1 2>&1 | command2 command1 |& command2 ● Mute by redirecting to /dev/null file
  • 11. Named Pipes and Network and Signal Processing ● Network exec 9<>/dev/tcp/google.com/80 echo -e "GET / HTTP/1.0nn" >&9 while read line <&9; do echo $line; done ● Named Pipes mkfifo pipe while read l; do echo $l; done < pipe echo “hi” > pipe # on another terminal window ● Signal Processing #!/bin/bash function handle_signal () { echo "Hi man I got the signal" } trap "handle_signal; exit" SIGINT sleep 100
  • 12. Cool Stuff and GUI ● Install these: libnotify-bin, zenity, festival ● date '+%l oclock' | festival –tts ● zenity --list --hide-header --text="Are you coming today?" --checklist --column "" --column "" FALSE "Yes" FALSE "No" FALSE "May be" ● zenity --calendar --date-format="%Y/%m/%d" ● zenity --text="Select Hour" --title="Select Hour" --scale --min-value=0 --max- value=24 --value=17 ● zenity --text="Select Minutes" --title="Select Minutes" --scale --min-value=0 --max-value=59 --value=0 ● zenity --info --text="Did you know this info" ● zenity --error --text="There is an error" ● zenity --entry | festival --tts ● zenity --file-selection ● <progres command> | zenity --progress --auto-close ● notify-send -t 10 "hi man" "details"
  • 13. Launchers ● When you drag a file or folder onto a launcher it is sent as $1 to the launcher script
  • 14. Example Codes ● Bluetooth Obex-push NEW_FILE_NAME=`echo $1 | awk -vFS="/" '{print $NF;}'` ussp-push 00:22:65:89:22:E6@9 "$1" "$NEW_FILE_NAME" ● Close the computer when your browser finishes downloading your_file while true; do sleep 5; if [ -z "`fuser ~/your_file`" ]; then break; fi; done; sudo init 0 ● Tell me the time whenever I lock my screen or unlock it ● Simple spider using curl and wget ● Log your time easily and report to a Redmine service ● Think of more ...
  • 16. References http://www.linuxcommand.org/lts0040.php http://www.cyberciti.biz/faq/bash-for-loop/ http://linuxcommand.org/wss0160.php http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-10.html http://wiki.bash-hackers.org/syntax/redirection http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html