Changes

Jump to: navigation, search

OPS435 Lecture 8 - Bash

1,116 bytes added, 18:20, 22 March 2016
Arrays
* [http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html Arrays]
* To get the length of an array: ${#ArrayName[@]}
 
== In-class examples ==
 
for.sh:
 
<source lang="bash">
#!/bin/bash
 
#for I in `seq 10`
#do
#echo $I
#done
 
for ((I=0; $I<10; I++))
do
echo $I
done
</source>
 
arrays.sh:
 
<source lang="bash">
#!/bin/bash
 
#COLOUR1=red
#COLOUR2=green
#COLOUR3=blue
 
COLOURS=("red" "light green" "blue" "orange" "indigo")
 
#echo ${COLOURS[1]}
#echo ${COLOURS[*]}
 
#for ((INDEX=0; $INDEX<3; INDEX++))
for ((INDEX=${#COLOURS[@]} - 1; $INDEX >= 0; INDEX--))
do
echo "Array value at index $INDEX is ${COLOURS[$INDEX]}"
done
</source>
 
safecopy-shorter.sh:
 
<source lang="bash">
#!/bin/bash
 
COPYTODIR=$1
 
# Not valid characers in a filename:
# < > : " / \ | ? *
isValidFilename()
{
BADCHARS=('<' '>' ':' '"' '/' '\\' '|' '?' '*')
NAME=$1
for ((INDEX=0; $INDEX<${#BADCHARS[@]}; INDEX++))
do
#echo "See if $NAME contains ${BADCHARS[$INDEX]}"
if echo $NAME | grep ${BADCHARS[$INDEX]} > /dev/null
then
return 1
fi
done
return 0
}
 
for FILE in *
do
if isValidFilename "$FILE"
then
echo "$FILE is good"
else
echo "$FILE is bad"
fi
done
 
#cp -v $COPYFROMDIR/* $COPYTODIR/
</source>

Navigation menu