Jump to content

Read user input with bash?

- - - - -

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

#1
Crop

Crop

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
I've seen some installation scripts and other such scripts ask for user input (IE: Do you wish to continue? ) but I can't find an example when I now need it. How can I read user input to a variable in bash?

'Do you wish to continue?'

A yes would continue, no would exit. Anyone?

#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
You can use the 'read' function:

read continue
echo '$continue'

More information here: http://tldp.org/LDP/...sect_08_02.html

#3
phpforfun

phpforfun

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,236 posts
Why not make it a function :)

#!/bin/bash
echo would you like to continue?
read continue
if [ $continue == yes ]; then
echo "You want to continue..";
else
echo "You dont want to continue..";
fi

Be sure to put a space between if and [, and a space between the brackets and the words/variables
It will show:

Quote

justin@justin-laptop:~/Desktop$ ./if
would you like to continue?
yes
You want to continue..
justin@justin-laptop:~/Desktop$ ./if
would you like to continue?
no
You dont want to continue..
justin@justin-laptop:~/Desktop$

Checkout my new forum! http://adminreference.com/

#4
DigitalLinx

DigitalLinx

    Newbie

  • Members
  • PipPip
  • 12 posts
Also you can pass arguments to your script like this.
#!/bin/sh

echo "The first argument is $1"

echo "The second argument is $2"

sh script.sh argument_one argument_two


#5
asafe

asafe

    Programmer

  • Members
  • PipPipPipPip
  • 107 posts
One trick of those installation scripts is not need press enter or letting it be yes:
read -s -n1 -p "Do you wish continue?Y/n " key

case $key in

"Y" | "y") # continue ;;

"N" | "n") #quit;;

*) #continue;;

esac