I am trying to write a shell script which will read a file and counts the number of vowels in the file. The code which read the file is as follows -

while read -n 1 c
do
  l=$(echo $c | tr [:upper:] [:lower:])
  [[ "$l" == "a" || "$l" == "e" || "$l" == "i" || "$l" == "o" || "$l" == "u" ]] && (( v++ ))
done < $file

When I run the script, getting the error -
read: 22: Illegal option -n where 22 is the line number.
I am confused why -n option is not working in the script whereas read -n 1 c command is working fine from terminal.
Any suggestion is appreciated.
Thanks in advance.

Dani AI

Generated

The "Illegal option -n" error means the read builtin being executed does not support -n (that option is a bash extension). was right to suspect a different shell. The interactive prompt can be bash while the script is actually running under a POSIX /bin/sh (dash on many systems). Also note that the value of $SHELL reflects the user’s login shell, not the interpreter that runs a script.

Quick diagnostic and fixes:

  • Run the script explicitly with bash or execute it directly as an executable rather than invoking it with sh:
chmod +x script.sh
./script.sh
# or
bash script.sh
# avoid: sh script.sh
  • Check for DOS line endings that break interpreter recognition:
file script.sh
dos2unix script.sh    # if installed
  • Confirm which interpreter is actually running the script (for debugging):
ps -p $$ -o comm=

If portability is desired (avoid relying on bash-only features), count vowels using POSIX-friendly utilities instead of per-character read. Two simple alternatives that avoid shell-specific options:

tr -cd 'AEIOUaeiou' < file | wc -c
# or
grep -oi '[aeiou]' file | wc -l

Summary: the presence of a bash shebang and an interactive bash prompt doesn’t guarantee the script runs under bash — how the script is invoked matters. Either invoke it with bash (or make it executable and run it directly) or switch to a portable technique like the tr/grep examples above.

Recommended Answers

All 2 Replies

The only reason I can think about is that the shells are different. What is in the #! line of the script, and what system you are running at?

The script is run in bash shell.
The line with #! is -

#!/bin/bash

Also when I run the command echo $SHELL it outputs /bin/bash i.e. both command and script running in same shell. But the command is working, not the script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.