Operating System - HP-UX
1752800 Members
5575 Online
108789 Solutions
New Discussion юеВ

Re: implement option in script

 
SOLVED
Go to solution
kholikt
Super Advisor

implement option in script

Hi,

I am writing the following script to check the file owner permission whether Write bit is enabled or not. The problem with this script is I still have problem to get it work with directory.

if the input is a directory i need to check whether those files in the directory has any file with write permission enabled, if so I will skip the files but will continue to copy over the rest of the files that meet requirement to the target together with directory and their associate subdirectory.

Also I was thought to implement -s and -t in the script so that I do not need to worry about the TGT variable which is the target filesystem.
abc
5 REPLIES 5
kholikt
Super Advisor

Re: implement option in script

I have tried the following:

while [ $# -gt 0 ]
do
case "$1" in
-s) src=$2;;
-t) tgt=$2;;
*) break;;
esac
shift
done
echo "cp -pr $src $tgt"

but it cannot process -s -t together and will extend after the -s
abc
kholikt
Super Advisor

Re: implement option in script

I also tried the getopts but doesn't be able to use case st

while getopts s:t option
do
case "${option}"
in
s) src=${OPTARG};;
t) tgt=${OPTARG};;
*) break;;
esac
shift
done

echo "$src $tgt"
abc
Matti_Kurkela
Honored Contributor
Solution

Re: implement option in script

In your first example, when your option needs an argument, you must remember to shift both the option and its argument to successfully parse the options:

--------
#!/bin/sh
while [ $# -gt 0 ]
do
case "$1" in
-s)
src="$2"
shift #An extra shift here...
;;
-t)
tgt="$2"
shift #...and here
;;
*)
break
;;
esac
shift
done
echo "cp -pr $src $tgt"
--------

With getopts, you should indicate that both your options have arguments, so the correct optstring is "s:t:", not "s:t". When you're using getopts to parse options, don't use the "shift" command in the same loop.
-------
#!/bin/sh
while getopts s:t: option
do
case "${option}" in
s)
src="${OPTARG}"
;;
t)
tgt="${OPTARG}"
;;
*)
break
;;
esac
done

echo "$src $tgt"
-------

MK
MK
James R. Ferguson
Acclaimed Contributor

Re: implement option in script

Hi:

In my opinion, using 'getopts' as soon as you have more than one option and/or argument is the appropriate course.

Useful programs tend to sprout more useful features. Having begun with getopts() to handle options and arguments offers an easy-to-amend framework.

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: implement option in script

HI (again):

You have a growing number of questions with unassigned points. Only about 3-of-10 of the responses you have received have been scored:


Please take a few minutes to show us what helped you and to say "thanks".

...JRF...