Jump to content

A Shell script problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
Hi all,
I am doing a simple shell script, such that it should read data from the user through stdin and shouldn't display the letters, instead it should display * for each letter.
It is just like the password prompt...
For example: The output should be like this

Quote

Enter the password: *****
The number of * should be equal to the number of characters the user enters...

I have Coded the program, but it is not terminating....
Here is the code
#! /bin/sh

echo -n " Enter the password: "
while [ 1 ]
do
    read -s -n1 key
    echo -n "*"
    if [ "$key" == "\n" ]
    then
        echo -n "@@@"
        break
    fi
done

exit 0
The Program is working as I expected, but the while loop is going infinite.
I can understand that, the problem is in
if [ "$key" == "\n" ]
Can anyone tell me how to solve this issue...

#2
DarkLordoftheMonkeys

DarkLordoftheMonkeys

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 255 posts
There should be a space between the -n and the 1 in the read options. And break might only be breaking out of the if statement rather than the for loop. I had a similar problem when I was programming in C. If this is the case, you can put the for loop in a function and use return instead of break, so it exits the function, and therefore the loop.
Life's too short to be cool. Be a nerd.

#3
konsolebox

konsolebox

    Newbie

  • Members
  • Pip
  • 4 posts
In bash you can use $'\n' instead. In other shells that does not support $'\n', you can simply use '<newline>'. You can also save it to a variable first then use the variable for the comparison.
# a

[ "$key" = $'\n' ]  # no need to use ==

# b

[ "$key" = '
' ]

# c

newline='
'
[ "$key" = "$newline" ]