0% found this document useful (0 votes)
11 views2 pages

Bash Scripting Operators and Structures

Uploaded by

florin_probe-1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Bash Scripting Operators and Structures

Uploaded by

florin_probe-1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arithmetic Operators Control Structures Function Definition

$ var=$(( 20 + 5 )) if [ condition ] # true = 0 function function-name ()


$ expr 1 + 3 # 4 then {
$ expr 2 - 1 # 1 # condition is true # statement1
$ expr 10 / 3 # 3 elif [ condition1 ] # statement2
$ expr 20 % 3 # 2 (remainder) then # statementN
$ expr 10 \* 3 # 30 (multiply) # condition1 is true return [integer] # optional
elif condition2 }
String Operators then
# condition2 is true Functions have access to script variables, and may have
else local variables:
Expression Meaning # None of the conditions is true
${#str} Length of $str fi $ local var=value
${str:pos} Extract substring from $str at
$pos case expression in
pattern1) execute commands ;; Arrays
${str:pos:len} Extract $len chars from $str at
$pos pattern2) execute commands ;;
esac $ vars[2]=”two” # declare an array
${str/sub/rep} Replace first match of $sub with $ echo ${vars[2]} # access an element
$rep while [ true ] $ fruits=(apples oranges pears) # populate array
${str//sub/rep} Replace all matches of $sub with do $ echo ${fruits[0]} # apples - index from 0
$rep # execute commands $ declare -a fruits # creates an array
${str/#sub/rep} If $sub matches front end of $str, done
echo "Enter your favourite fruits: "
substitute $rep for $sub
until [ false ] read -a fruits
${str/%sub/rep} If $sub matches back end of $str, echo You entered ${#fruits[@]} fruits
do
substitute $rep for $sub # execute commands for f in "${fruits[@]}"
done do
Relational Operators echo "$f"
for x in 1 2 3 4 5 # or for x in {1..5} done
Num String Test do
echo "The value of x is $x"; $ copy=( "${fruits[@]}" ) # copy an array
-eq = Equal to $ array=( "${fruits[@]}" "grapes" ) # add to end
done
== Equal to $ unset fruits[1] # delete one element
-ne != Not equal to LIMIT=10 $ unset fruits # delete array
-lt \< Less than for ((x=1; x <= LIMIT ; x++))
-le Less than or equal to do Array elements do not have to be sequential - indices are
-gt \> Greater than echo -n "$x " listed in {!fruits[@]}:
done
-ge Greater than or equal to
for i in ${!fruits[@]}
-z is empty for file in *~ do
-n is not empty do echo fruits[$i]=${fruits[i]}
echo "$file" done
File Operators done
All variables are single element arrays:
break [n] # exit n levels of loop $ var=”The quick brown fox”
True if file exists and...
continue [n] # go to next iteration of loop n up $ echo {var[0]} # The quick brown fox
-f file ...is a regular file
-r file ...is readable Function Usage String operators can be applied to all the string elements
-w file ...is writable in an array using ${name[@] ... } notation, e.g.:
-x file ...is executable function-name arg1 arg2 arg3 argN $ echo ${arrayZ[@]//abc/xyz} # Replace all
-d file ...is a directory occurrences of abc with xyz
-s file ...has a size greater than zero. n.b. functions must be defined before use...
User Interaction Data and Time BASH Quick Reference Card
echo -n "Prompt: " $ start=`date +%s` “All the useful stuff on a single card”
read $ end=`date +%s`
echo "You typed $REPLY." $ echo That took $((end-start)) seconds #!/bin/bash
$ date +"%c" -d19540409 $ chmod ugo+x shell_script.sh
echo -n "Prompt: " Fri 09 Apr 1954 12:00:00 AM GMT
read response $ bash [options] [file]
echo "You typed $response." Case Conversion Options
-x show execution of [file]
PS3="Choose a fruit: " $ in="The quick brown fox"
select fruit in "apples" "oranges" "pears" -v echo lines as they are read
$ out=`echo $in | tr [:lower:] [:upper:]`
do $ echo “$out”
if [ -n "$fruit" ] THE QUICK BROWN FOX Variables
then
break $ var=”some value” # declare a variable
Preset Variables
fi $ echo $var # access contents of variable
echo "Invalid choice" $ echo ${var} # access contents of variable
done $HOME User’s home directory $ echo ${var:-”default value”} # with default
$HOSTNAME Name of host $ var= # delete a variable
$ dialog --menu "Choose" 10 20 4 1 apples 2 \ $HOSTTYPE Type of host (e.g. i486) $ unset var # delete a variable
oranges 3 pears 4 bananas 2>/tmp/ans $PWD Current directory
$ fruit=`cat /tmp/ans` $REPLY default variable for READ and SELECT Quoting - “$variable” - preserves whitespace
$ echo $fruit
$SECONDS Elapsed time of script
Positional Variables
$ zenity --list --radiolist --column "Choose" \
$TMOUT Max. script elapsed time or wait time
--column "Fruit" 0 Apples 0 Oranges 0 Pears 0 \ for read
$0 Name of script
Bananas > /tmp/ans
$ fruit=`cat /tmp/ans`
$1-$9 Positional parameters #1 - #9
References ${10} to access positional parameter #10 onwards
$ echo $fruit
$# Number of positional parameters
Linux Shell Scripting Tutorial - A Beginner's handbook
Reading Input from a File "$*" All the positional parameters (as a single
[Link]
word) *
exec 6<&0 # ‘Park’ stdin on #6 ures/lsst/
"$@" All the positional parameters (as separate
exec < [Link] # stdin=file "[Link]" BASH Programming Introduction, Mike G
strings)
read # from stdin [Link]
until [ -z "$REPLY" ] Advanced BASH Scripting Guide, Mendel Cooper
$? Return value
do [Link]
echo “$REPLY” # lists [Link] set [values] - sets positional params to [values]
read
Copyright & Licence set -- - deletes all positional parameters
done shift [n]- move positional params n places to the left
exec 0<&6 6<&- # restore stdin
echo -n "Press any key to continue" This Reference Card is Copyright (c)2007 John McCreesh
jpmcc@[Link] and is licensed under the Creative Command Substitution
read
Commons Attribution-Noncommercial-Share Alike 2.5 UK:
$ var=`ls *.txt` # Variable contains output
Trapping Exceptions Scotland License. To view a copy of this license, visit
$ var=$(ls *.txt) # Alternative form
[Link] $ cat myfile >/dev/null # suppress stdout
TMPFILE=`mktemp` sa/2.5/scotland/ or send a letter to Creative Commons, $ rm nofile 2>/dev/null # suppress stderr
on_break() 543 Howard Street, 5th Floor, San Francisco, California, $ cat nofile 2>/dev/null >/dev/null # suppress
{
94105, USA. both
rm -f $TMPFILE
exit 1
} This version dated:20/02/07
trap on_break 2 # catches Ctrl+C

You might also like