Shell scripting: if/or conditional statement

February 13, 2010 at 17:55:22
Specs: OS X, 2.16Ghz/2GB
Learning how to shell script.

Is there a cleaner way of specifying this if/or conditional? The below works, but I'm
thinking there's got to be a more efficient manner of listing each conditional..

Thanks in advance

#!/bin/bash

scriptname=`basename $0`;
swapfilename=.$scriptname.swp;

for i in `ls -A`
do
	if [ $i = $scriptname ] || [ $i = $swapfilename ] || [ $i = "tr1.sh" ] || [ $i = "tr2.sh" ]
		then
			echo "-Ignoring $i!"
	else
		newname=`echo $i | tr a-z A-Z`
		echo "-----Moving $i to $newname"
		mv $i $newname
	fi
done


See More: Shell scripting: if/or conditional statement

Report •

#1
February 14, 2010 at 05:17:04
I guess the CASE command is more suite ... I don't know the syntax by heart, but it's something like ...

BEWARE, this is untested, it's something in this style

for i in `ls -A`
do
case ($1) in

$scriptname|$swpname|tr1.sh|tr2.sh)
echo "-Ignoring $i!";;

*)
newname=`echo $i | tr a-z A-Z`
echo "-----Moving $i to $newname"
mv $i $newname;;

esac
done


Report •

#2
February 14, 2010 at 13:08:59
Okay, thanks. I'll look up case statements.

Report •

#3
February 14, 2010 at 13:19:13
If your script works the way it is, fine; but you asked for efficiency changes so here
is my take:

1) If you want the ls command output objects to be on one line, make sure to use a -1 option such as this: ls -1A

2) I would use a while loop instead of a for loop. If the output of the ls command has more than one column you would have a problem. For more info tatke a look at this link:
http://partmaps.org/era/unix/award....

3) You really should surround the arguments to the tr command with quotes. Note that I optionally use the newer syntax - lower and upper .


#!/bin/ksh

scriptname=`basename $0`;
swapfilename=.$scriptname.swp

# UNTESTED
ls -1A |while read i
do
   case "$i" in
      $scriptname|$swapfilename|tr1.sh|tr2.sh)
         echo "-Ignoring $i!";;
      *)
      newname=`echo "$i"| tr "[:lower:]" "[:upper:]"`
      echo "-----Moving $i to $newname"
      mv "$i" $newname;;
   esac
done


Report •
Related Solutions


Ask Question