Hi Can anybody please explain how the below script works and if there is any problems with it? The script is part of an archival process but it keeps crashing out.
#!/sbin/sh -
clear
purgelist="/var/opt/moto/live/scripts/old_messages_purge_list"
for i in `cat $purgelist`
do
filepath=`echo $i|sed 's/^[ ]*\([^= ]*\)[= ].*$/\1/g'`
filedays=`echo $i|sed 's/^[^=]*=\(.*\)[| ].*$/\1/'`
ext=`echo $i|sed 's/^[^|]*|\(.*\)$/\1/'`
find $filepath -name '*'$ext -mtime $filedays -print -exec rm {} \;
done
The main problem here is the pipe character "|" towards the end of each string. This character is wrecking the syntax of your expanded "for" line and each echo statement because shell is interpreting it.
We can use unix "dirname" and "basename" commands to break the long line into the directory name and the trailing string. Then extracting the two parameters can be simplified by changing the pipe character "|" to an equals sign "=" to create a common delimiter for each field.
To handle a string containing awkward characters such as pipe, we must keep it between double quotes characters and avoid expansion by shell.
For example replacing the "for" loop with a "while" loop:
#!/sbin/sh
clear
purgelist="/var/opt/moto/live/scripts/old_messages_purge_list"
cat ${purgelist} | while read line
do
filepath="`dirname ${line}`"
# Extract string containing ext and filedays
# Change pipe character to = character to make common delimiter
work=`basename "${line}"|sed -e "s/\|/=/g"`
filedays=`echo "${work}"|cut -f2 -d=`
ext=`echo "${work}"|cut -f3 -d=`
echo "filepath=${filepath}"
echo "ext=${ext}"
echo "filedays=${filedays}"
done