if [[ $# -ne 1 ]] || [[ $# -gt 1 ]]
then
echo "Required one input file"
echo "Enter a file to get char count:"
read $FILE_NAME
if [[ -f $FILE_NAME ]]
then
echo "valid file"
else
echo "Not a valid file."
fi
When run as read_file.ksh detail.csv or read_file.ksh ~/ded/incoming/detail.csv it works fine. But when i run the script alone w/out the argument as
as given in the script it prompts as
and when i enter the file along with the full path, its not recognized as a file.
I think it makes no sense to check if there is not exactly 1 parameter or more than 1. More than 1 is also not equal 1.
When using read into a variable, leave out the leading $.
Your script could look like:
if [[ $# -ne 1 ]]; then
echo "Required one input file"
exit 1
fi
echo "Enter a file to get char count:"
read FILE_NAME
if [[ -f $FILE_NAME ]]; then
echo "valid file"
else
echo "Not a valid file."
fi
exit 0
Your concern is correct. The requirement here is the user need to enter only one file as argument. If he enters more than one file or none it prompts for a input file.
Actually if he enters one file as read_file.ksh detail.csv it works fine - as i have kept this check in diff part of the script which i have not included in the original post. Below is the full script.
if [[ $# -ne 1 ]] || [[ $# -gt 1 ]]
then
echo "Required one input file"
echo "Enter a file to get char count:"
read FILE_NAME
if [[ -f $FILE_NAME ]]
then
echo "valid file"
else
echo "Not a valid file."
else
FILE_NAME=$1
if [[ -f $1 ]]
then
echo "valid file to get char count"
else
echo "Not a valid file to get char count."
fi
Interesting you are correct. When the filename is entered into the read statement rather than on the command line it does indeed not expand the ~username.
Fix highlighted in script below.
script_name=`basename $0`
param_count=$#
case ${param_count}
in
0)
echo "Enter a file to get char count:"
read FILE_NAME
;;
1) FILE_NAME="$1"
continue
;;
*) echo "Usage: ${script_name} filename"
exit 1
;;
esac
FILE_NAME=`eval echo "${FILE_NAME}"`
if [ -f "${FILE_NAME}" ]
then
echo "valid file : ${FILE_NAME}"
else
echo "Not a valid file : ${FILE_NAME}"
fi
Oops. Delete "continue" line - it's a paste error.
The eval is only to cause shell to look at special shell variables (like ~) after the shell program has been interpreted. I've also seen it used where a script generates an environment variable name on the fly.
ok. Guess the continue for case statement doesn't work in ksh. When i ran the script in /bin/sh it returned no error for the continue statement.
Thanks much!