Hi All,
I have created one function for KSH and was running well with one parameter input since I just had to use $1 to get the parameter.
Now I want to do loop for each parameter(actually filenames) . I have try to use do loop, but $i does not resolve to parameter instead it resolves to 1, 2, 3 etc...
example,
func()
echo There are ${#} parameters..
i=1
while (( i <= ${#} ))
do
if [ ! -f $("$i")];
then
echo "Error $i does not exist!"
else
echo "Error $i does exist, please proceed".
fi
(( i+=1 ))
done
}
Please advice.
#!/bin/ksh
function process_files
{
echo There are ${#} parameters..
k=1
while [ $k -le ${#} ]
do
eval i=\${$k}
if [ ! -f "$i" ]
then
echo "Error $i does not exist!"
else
echo "Error $i does exist, please proceed".
fi
(( k = k + 1 ))
done
}
1 Like
Hello rdrtx1,
I think in shell unlike awk
there is no need for function function_name
, you could put directly as function_name {....}
, so it could be written as follows.
#!/bin/ksh
process_files ()
{
echo There are ${#} parameters..
for i in $*
do
if [ ! -f "$i" ]
then
echo "Error $i does not exist!"
else
echo "Error $i does exist, please proceed".
fi
done
}
Thanks,
R. Singh
Include parentheses in the other function definition format:
process_files ()
Worked like charm. thanks!
---------- Post updated at 02:57 PM ---------- Previous update was at 02:41 PM ----------
It seems you edited and replaced with your previous answer. It worked for me. Thanks anyways!
Note: the natural loop through the arguments is the for
loop.
func(){
# the for loop defaults to 'in "$@"'
for arg
do
if [ -f "$arg" ]
then
echo "Error '$arg' does exist, please proceed."
else
echo "Error '$arg' does not exist!"
fi
done
}
# pass all arguments of this shell to func()
func "$@"
func file1 file2 "filename with spaces"
Note that "$@"
is preferrable to $*
because it does not split on words.