S# in a for loop - concatenate $(loop counter)

Hi,

hope I am posting in the right section.

My problem is that I have 2 or more arguments passed and I want to check if the arguments passed exists or not.
The first argument should not exist and the remaining others should exist.

example:

./shells.sh argument1 argument2 argument3

#!/bin/bash
if [ $# -eq 1 ]
then 
	echo "There should be two or more filenames."
	exit 1
fi
if [ -f $1 ]
then
	echo "Sorry, $1 file should not exist"
else
	num=$#
	echo "number of files is: $num"	
	for var in `seq 2 $num`
	do	
		if [ -f $`$var` ]
		then
			echo "$var exists"
		fi
	done	
fi

how do I change this line

if [ -f $`$var` ]

so that it would become

if [ -f $2 ] 

or

 if [ -f $3 ] 

and so on..

I tried many variations but I always get error like substitution error or command not found.

I would really appreciate your replies. Thanks!

Not quite sure that I understand your reasoning, nevertheless, here it goes; a shut in the dark:

else
	shift
	
	for arg in $@
	do	
		if [ -f "$arg" ]
		then
			echo "$arg exists"
		fi
	done	
fi
1 Like

thanks!

I'll try this.

thank you so much! this works! :slight_smile:

I'd make one small change to Aia's suggestion:

for arg in "$@"

Quoting $@ preserves any whitespace that might have been a part of the parameter on the command line. Unfortunately people do create filenames which have spaces, and if the command line were something like this

script-name nosuchfile "my big file" 

using $@ without the quotes would cause the loop to execute and test "my" "big" and "file" as three separate names, rather than the single name entered on the command line.

Filenames with spaces are a personal pet peeve, and your environment might not have any for you to worry about, but from a more generic command line processing perspective, knowing the difference between $@ and "$@" might make a difference as you write scripts in future.

1 Like

thanks for adding! I really appreciate it. Thank you also for sharing the difference of $@ with and without double quotes. Thanks!