Difference between revisions of "Tutorial: A bit of Bash"

From dftwiki3
Jump to: navigation, search
(Variables)
(e)
Line 32: Line 32:
 
=Script Parameters=
 
=Script Parameters=
  
* assume '''doit.sh''' is a script and it is called as follows: '''<tt>doit.sh 8 2000 50</tt>'''
+
* assume '''doit.sh''' is a script and it is called as follows:  
 +
 
 +
  '''doit.sh 8 2000 50'''
 +
 
 
* To get the arguments inside the script:
 
* To get the arguments inside the script:
  
Line 45: Line 48:
 
     exit
 
     exit
 
  fi
 
  fi
 +
 +
=Displaying strings and various quantities=
 +
=Getting the length of a string variable=
 +
 +
name="toto.txt"
 +
echo "length of $name = ${#name}"      #will output 8
 +
 +
=Getting extension and name (without extension) of a file=
 +
 +
fullPath="/usr/local/bin/toto.txt"
 +
fileName="${fullPath##*/}"
 +
echo "file name with extension = $fileName"
 +
extension="${fullPath##*.}"
 +
fileName="${fileName%.*}"
 +
echo "fullPath = $fullPath"
 +
echo "fileName without extension = $fileName"
 +
echo "extension = $extension"

Revision as of 11:17, 26 November 2013

--D. Thiebaut (talk) 11:03, 26 November 2013 (EST)


A quick review of some useful Bash commands that can be used on the command line, or that can be included in bash scripts

Creating a bash script

  • first line should contain name of bash shell
#! /bin/bash
  • make the script executable
chmod +x scriptname


Variables

  • Declaration
file="hello.txt"
file=`ls -1 *.txt | head -1`     # get the first .txt file in the directory
  • In expressions: put a $ in front of it!
URL="http://cs.smith.edu/dftwiki/images/"
file="toto.png"
pathFile=$URL$file
file="alpha"
pathFile=$URL${file}.png      # add braces if string needs to be concatenated to variable

Script Parameters

  • assume doit.sh is a script and it is called as follows:
 doit.sh 8 2000 50
  • To get the arguments inside the script:
NP=$1    # will get 8
N=$2     # will get 2000
M=$3     # will get 50
  • To test if the number of parameters is 3 inside the script:
if [ "$#" -ne 3 ]; then
    echo "syntax: doit.sh NP N M"
    exit
fi

Displaying strings and various quantities

Getting the length of a string variable

name="toto.txt"
echo "length of $name = ${#name}"      #will output 8

Getting extension and name (without extension) of a file

fullPath="/usr/local/bin/toto.txt"
fileName="${fullPath##*/}"
echo "file name with extension = $fileName"
extension="${fullPath##*.}"
fileName="${fileName%.*}"
echo "fullPath = $fullPath"
echo "fileName without extension = $fileName"
echo "extension = $extension"