LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   My script not giving result with 2 or more arguments (https://www.linuxquestions.org/questions/programming-9/my-script-not-giving-result-with-2-or-more-arguments-764695/)

baigmd 10-26-2009 10:36 PM

My script not giving result with 2 or more arguments
 
Hi,

Can anyone help....my shell script is giving correct results with 2 or more arguments. 0 or 1 arguments it is working fine, Here is the script

#!/bin/sh
sname=$(basename $(readlink -nf $0))
echo "This is $sname, running at $(date)"
echo "It is running on $(hostname)"
echo "Script being run by"
echo " User $(grep "^$USER:" /etc/passwd | cut -d: -f1)"
echo " UID $(grep "^$USER:" /etc/passwd | cut -d: -f3)"
echo " who is really $(grep "^$USER:" /etc/passwd | cut -d: -f5)"
echo ""
echo "Called with $# arguments"
for ((i=0 ; i < $# ; i++))
do
if test -f "$*"
then
echo "-> Argument $* is a file"
ls -l $*
else
echo "-> Argument $* either is not a regular file, or doesn't exist"
fi
done

David the H. 10-27-2009 12:12 AM

'$*' means all arguments together as a single line. To echo all arguments as individual entries, use '$@'. As it is, your last section is testing the whole set of arguments every iteration of the loop.

Besides, you don't need to be so complex to loop through all the existing arguments.
Code:

for i in "$@"; do

if test -f "$i"
then
echo "-> Argument $i is a file"
ls -l $i
else
echo "-> Argument $i either is not a regular file, or doesn't exist"
fi

Finally, please use [code][/code] tags around your code, for readability and to preserve formatting.

indiajoe 10-27-2009 12:41 AM

Or.. you can also use the shift command
 
Hi,
You can also use the shift command to do the same..
As shown below. It is just the last part of your script..
Code:

while [ -n "$1" ]
do
if test -f "$1"
then
echo "-> Argument $1 is a file"
ls -l "$1"
else
echo "-> Argument $1 either is not a regular file, or doesn't exist"
fi
shift
done

Just another way of doing the same thing...
Cheers
indiajoe


All times are GMT -5. The time now is 06:31 PM.