Pass command line argument to variable

Hi,

I had written a shell script to pass command line argument to variable in a function.

Here is my code:

main

if [-f $1]; then
  .$1
  echo $1
  get_input_file
else
  echo "input file $1 is not available"
fi
 
get_input_file()
{
FILE = "$1"
echo $FILE
}

but I am getting error as FILE not found.
Can anyone correct me in this script. I am a new to shell scripting.
Thanks a lot in advance.

You need space around [ test as if [ -f $1 ]; then
No space when you declare variables FILE="$1"

#!/bin/bash -x

get_input_file()
{
FILE="$1"
echo $FILE
}

if [ -f $1 ]; then
  # .$1
  echo $1
  get_input_file $1
else
  echo "input file $1 is not available"
fi

Thanks for reply.
But the error still exists, after changing
input_file = " $1 "

echo $input_file

Please help me out.

Please reread the 2nd line of the post of danmero.

Hi
Try this code :

get_input_file()
{
FILE=$1
echo $FILE
}
if [ -f $1 ]; then
  . $1
  echo $1
  get_input_file $1
else
  echo "input file $1 is not available"
fi

Thanks a lot dashing201. Its working fine.

I just update the code as below,

get_input_file()
{
FILE=$1
echo $FILE
TYPE=`echo $FILE | cut -d "_" -f 3`
echo "Type is $TYPE"
EXTN=`echo $FILE | cut -d "." -f 5`
echo "Extension is $EXTN"
}

And I am putting some values in input file as,

abcdefghij;20100903040607;1234567891;GLOBAL;

but getting output as,

Sample.ksh[97]: abcdefghij:  not found.
Sample.ksh[97]: 20100903040607:  not found.
Sample.ksh[97]: 1234567891:  not found.
Sample.ksh[97]: GLOBAL:  not found.
MigBIOS_CR_GLOBAL_20100924021422.CSV
Type is
Extension is

Could you please tell me why error is occurring for each value in input file and the values of TYPE and EXTN are not getting displayed as GLOBAL and CSV respectively?
Could you please tell me where I did the mistake in code?

Hi

You cannot have two different delimiters to extract fields. In your case you are using '.' as well as '_'

Second cut delimiter column # is wrongly put as 5 instead of 2.

get_input_file()
{
FILE=$1
echo $FILE
TYPE=`echo $FILE | cut -d "_" -f 3`
echo "Type is $TYPE"
EXTN=`echo $FILE | cut -d "." -f 2`
echo "Extension is $EXTN"
}

### Function Call
get_input_file MigBIOS_CR_GLOBAL_20100924021422.CSV

Output

$ sh script.sh
MigBIOS_CR_GLOBAL_20100924021422.CSV
Type is GLOBAL
Extension is CSV

Thanks a lot Kmuthu_gct.

Now I am able to print values of TYPE and EXTN.

but still I am getting errors for input file data as,
Sample.ksh[97]: abcdefghij: not found.
Sample.ksh[97]: 20100903040607: not found.
Sample.ksh[97]: 1234567891: not found.
Sample.ksh[97]: GLOBAL: not found.

Could you please help me out.

Hi Poonamol

Just comment/remove this line in your code where you are checking for file.

 
#. $1

Thanks a lot :slight_smile: