Linux Blog

Shell Script to get user input

Filed under: Shell Script Sundays — TheLinuxBlog.com at 2:06 am on Sunday, January 27, 2008

Creating a shell script to get input is rather easy. Shell scripts prompting input are generally more user friendly too. In this article I’ll show you how to read input from the bash shell. Take the example below:

<pre>
#!/bin/bash
 
echo "Shell Script To Get User Input";
 
while read inputline
do
what="$inputline"
echo $what;
 
if [ -z "${what}" ];
then
exit
fi
 
done

All it does is echo’s the introduction “Shell Script To Get User Input” and then goes right to the bash read input loop. The next line makes a variable so that we can echo it out and also check if its empty with the if [ -z part. If the script is empty we exit, if not we loop around another time.

This is a very basic example but it can easily be modified so that you can use bash to grab user input. If you have any trouble with this script drop me a comment and I’ll be happy to help you out.

Man Pages for commands in this post »

echo
echo

32 Comments »

248

Comment by Nicole Freeman

January 27, 2008 @ 9:48 pm

Hi,

I’m trying to compile a boot script that accepts user input on the HOSTNAME variable (SUSE Linux during the boot process, puts this user-provided hostname in the /etc/HOSTNAME file, and reboots the system. Can you plz help me with this? I’m new to scripting and was hoping to find some help on this…

TIA,
-Nicole

251

Comment by Owen

January 28, 2008 @ 10:20 am

So, you are trying to change the host name by user input on boot up? Are you saying after user input it puts it in the hosts file but reboots instead of booting up?

255

Comment by Nicole Freeman

January 29, 2008 @ 1:17 am

Correct, the inital hostname would be assigned randomly by DHCP. I was hoping to run this script postinstall so that the user was free to choose the hostname, and a reboot would “cleanly” set it by adding it to the /etc/HOSTNAME file.

Thanks much!!!

258

Comment by Owen

January 29, 2008 @ 11:13 am

I’m not familiar with SuSe but in some other distributions there are network configuration scripts. Maybe you could try to strace that program and see what it is doing. Check out http://www.thelinuxblog.com/uploads/netconfig
It creates temp files for all of the files needed and if that is correct I believe it copies them. If you need any more help let me know.

269

Comment by Nicole Freeman

January 31, 2008 @ 11:48 am

Thanks Owen, I’ll look at this script and see how I can use it to get my job done!
Appreciate your help on this.

270

Comment by Owen

January 31, 2008 @ 11:58 pm

Anytime :) Let me know if you need any more help and feel free to comment on any posts with questions

282

Comment by Nicole Freeman

February 4, 2008 @ 11:55 am

Hi Owen,

Yaay! I was able to use portions of the netconfig script to copy the host and domainname during system startup. It worked extremely well!

I was also requested to however (in the same startup script), provide a couple of screens to add a user to the system, and have the user type his/her password while running a bg sanity check to ensure that the userid is not a duplicate.

I tried drafting this part on my own and it looked awful :-( Could you help me with this please?

TIA,
Nicole

290

Comment by Owen

February 5, 2008 @ 11:32 am

I’ll look into it.

adduser is a command, you might be able to use expect if your PC has it. useradd does require a unique ID.

294

Comment by Nicole Freeman

February 5, 2008 @ 5:05 pm

Hi Owen,

The SLES version I’m using only has the “useradd” binary, which I guess is good from what you just mentioned wrt its internal duplicate check process.

Meanwhile this is the portion of netconfig I’ve used in my boot script. The last line of the script really did it for me.

Thank you so much, and I’m really sorry for the trouble!

-Nicole

# Main loop:
while [ 0 ]; do
cat < $TMP/tempmsg
First, we’ll need the name you’d like to give your host.
Only the base hostname is needed right now. (not the domain)

Enter hostname:
EOF
dialog –title “ENTER HOSTNAME” –inputbox “`cat $TMP/tempmsg`” 11 65 \
$HOSTNM 2> $TMP/SeThost
if [ $? = 1 -o $? = 255 ]; then
rm -f $TMP/SeThost $TMP/tempmsg
exit
fi
HOSTNM=”`cat $TMP/SeThost`”
rm -f $TMP/SeThost $TMP/tempmsg
if [ ! “$HOSTNM” = “” ]; then
break;
fi
done

while [ 0 ]; do
cat < $TMP/tempmsg
Now, we need the domain name for this machine, such as:

example.org

Do not supply a leading ‘.’

Enter domain name for $HOSTNM:
EOF
dialog –title “ENTER DOMAINNAME FOR ‘$HOSTNM'” –inputbox \
“`cat $TMP/tempmsg`” \
14 64 $DOMAIN 2> $TMP/SeTdom
if [ $? = 1 -o $? = 255 ]; then
rm -f $TMP/SeTdom $TMP/tempmsg
exit
fi
DOMAIN=”`cat $TMP/SeTdom`”
rm -f $TMP/SeTdom $TMP/tempmsg
if [ ! “$DOMAIN” = “” ]; then
break;
fi
done

echo $HOSTNM.$DOMAIN > etc/HOSTNAME

295

Comment by Owen

February 5, 2008 @ 5:16 pm

Glad that worked out for you.

I don’t think that useradd has a duplicate ID script.
It just so happens that adduser is also a Slackware script. Maybe you could use part of this too.

Its no trouble at all this is what The Linux Blog is here for :) Just make sure you drop by from time to time and leave me more comments :D

299

Comment by Nicole Freeman

February 7, 2008 @ 2:51 pm

Hi Owen,

Thanks for the adduser script.

I now have both pieces of code and wish to have them execute automatically when a “guest” user logs in.
The goal of this entire exercise is that each user will be given a laptop and a guest account with no password.

Once they login as “guest” they should be able to set a hostname of their choice (using portions of the netconfig script); and also be able to create their own userid’s.

I gave the “guest” user sudo perms (with NOPASSWD) on these scripts and put the absolute paths to these scripts in the .bashrc file of the “guest” user, but the GUI wouldn’t come up when I tried logging in as the guest user.

I know I’m doing something fundamentally wrong here. Once this is done; I should be all set.

Thank you.
-Nicole

300

Comment by Owen

February 7, 2008 @ 3:00 pm

What is your default run level?

Also, once we get this figured out can we write a blog post about it?

I’m not familiar with SLED but I don’t think that it needs any special user settings to startx.

Can you post the rest of the script?

– Owen.

301

Comment by Nicole Freeman

February 7, 2008 @ 4:50 pm

The default run level is 5. The GUI login screen comes up but what I mean is that, the script needs to be specified in a “bash-friendly” manner as it won’t bring up the guest users login screen but would simply show a blank screen after entering the username/password at the GUI login screen. So I’m guessing it has to do with how its specified in .bashrc. We can surely blog this once we’re done.

Thanks!

302

Comment by Owen

February 7, 2008 @ 5:13 pm

All right, Maybe change the run level to multi user no X. This time see if once its done you can just run the command startx.

370

Comment by Phani

February 28, 2008 @ 12:55 am

Hi Owen

I am trying to export the user input to a variable. I did used the example provided by you, but the loop is never ending. I want to stop the loop once the user has entered his input, so that I can export that input to another variable which can be used for other script.

Kindly help by any suggestion in achieving this task.

Thanks,
Phani.

371

Comment by Owen

February 28, 2008 @ 1:20 pm

Hi Phani,

This should work:

while read inputline
do
what=”$inputline”
done

echo $what

Hope this helps, Owen.

372

Comment by Phani

February 28, 2008 @ 6:49 pm

Thanks Owen
But its not working, the loop is not ending and the input is not passing to the variable.

Any help is much appreciated.

Thanks,
Phani.

373

Comment by Owen

February 29, 2008 @ 11:44 am

Phani,

Try this script: input.sh It should exit the loop with no problem.

739

Pingback by The Linux Blog » tweeting from the command line

June 29, 2008 @ 12:25 pm

[…] If you’d like more information on how this works read this article: Shell Script to get user input […]

Comment by MBN

October 9, 2008 @ 8:48 pm

hiya

looked at your above script but i want to use it the oppersite way around… more to check that user input is not blank?

Comment by TheLinuxBlog.com

October 10, 2008 @ 9:23 am

@MBN the -z string returns True if the length of string is zero.
Currently, if the user types an empty string, or nothing the script exits.
Removing -z in the if statement will exit if the user types something in.

Hope this helps,

– Owen.

Comment by MBN

October 13, 2008 @ 8:50 am

Still a little bit lost :(

This is what i’m trying to do and my code that’s all $%^ up

I’m trying to get a user to enter another users name which in turn checks to see if that users home folder exists.

#!/bin/bash

cd /home

echo "Please enter a users name and press [Enter]";

while read username

do

blank="$username"

echo $blank;

if [ -z "${blank}" ]; then

echo "That was empty, Please try again"

else

echo "Checking now . . . . "

fi

done

if [ -d $username ]; then

echo "That user exists"

else

echo "No such user" # am I able to loop this back up to the top for user to enter user name?

fi

Sorry about the shocking coding i’m still trying to learn

Comment by MBN

October 13, 2008 @ 8:56 am

Oh and this is the not out put which for a newbie don’t look to good :(

: command not found
Please enter a users name and press [ENTER] :
: command not found
taskb.sh line 31: syntax error near unexpected token `fi’
taskb.sh line 31: `fi’

Comment by pratik

September 9, 2010 @ 7:15 am

Hi i want to know how to take in input from the user in a pop up?? is there any option for the same??

Comment by TheLinuxBlog.com

September 10, 2010 @ 8:43 am

Sure, check out this graphical shell scripting article and do something like this: Xdialog --inputbox "Enter your text here" 8 30

Comment by kksoni

November 20, 2010 @ 11:16 am

how to validate that my format of user parameteres in this format

LIKE :

AUS 100 USA

mean checked this type or format is given on input is right or not

Comment by TheLinuxBlog.com

November 20, 2010 @ 2:01 pm

Hey kksoni I think you’re talking about input validation.
There are a few ways to do it. One is to use if statements, another is by using grep and regular expressions. Check out this page for a few examples.

Comment by CaliDude

December 14, 2010 @ 10:15 am

Hi I am looking for a script that can 1.That creates the name of a new host “test-system-x”2. select a IP range from 1-250, 3. But also when I input the host name like 1 or 2 it will also give the ip started from 10 so it would look like this

test-system-11
1.192.168.0.11
test-system-12
2.192.168.0.12

please help anything to get me started would be AWESOME!!!!

Comment by TheLinuxBlog.com

December 14, 2010 @ 10:24 am

Hey, I’ll see what I can come up with. The first thing would be to use hostname to set the hostname, eg. sudo hostname test-system-11; next would be to use ifconfig to set the ipaddress, gateway etc. You can use the input from this post to get the parameters, if the last field of the hostname would be numbers you can use cut to extract that. Something like: echo $HOST_NAME | rev | cut -d – -f 1 would probably work

Comment by CaliDude

December 14, 2010 @ 10:32 am

Thanks!!!! I this script but the part im missing is how to get the variables correctly so that when ready I can just input the name and the last octet of the ip address

#!/bin/bash

# Get next available IP (loop through subnet and find first IP that doesn’t respond to ping)
IP=$(for i in `seq 1 254`; do if (! ping -q -c 1 192.168.0.{i} 1>/dev/null 2>&1); then echo ${i}; break; fi; done)

# Delete current IP address from config file
sed ‘/IPADDR/d’ /etc/sysconfig/network-scripts/ifcfg-bond0 > /etc/sysconfig/network-scripts/ifcfg-bond0.new

# Add configuration option for new IP address
echo “IPADDR=192.168.1.${IP}” >> /etc/sysconfig/network-scripts/ifcfg-bond0.new

# Replace network interface configuration
mv /etc/sysconfig/network-scripts/ifcfg-bond0.new /etc/sysconfig/network-scripts/ifcfg-bond0

# Same with hostname
sed ‘/HOSTNAME/d’ /etc/sysconfig/network > /etc/sysconfig/network.new
echo “HOSTNAME=newhostname” >> /etc/sysconfig/network.new
mv /etc/sysconfig/network /etc/sysconfig/network

echo “Reboot for changes to take effect…”

im kinda new to the bash scripting world so im kinda in the mud with this and your help would again be awesome!!

But I think my script is a little off my counterpart got this working in windows but he cant help with stuff Linux stuff

this is what he made

[int]$a = read-host -Prompt “input CDS number”

if($a -lt 240 -and $a -gt 0){
# baspscfg -name 247Team -type 2
if($a -lt 10){
$hostname = “de-cds-win-0$a”
}
else{
$hostname = “de-cds-win-$a”
}
$ip = “10.8.40.$($a + 10)”
Write-Host “ip-adress $ip”
# netsh interface ip set address name=”247Team” static $ip 10.8.40.1 255.255.255.0. 1
# netsh interface dns set address name=”247Team” static 10.1.14.35
$computerinfo = Get-WmiObject -class win32_computersystem
#$computerinfo.Rename($hostname)
Write-Host “changed from $computerinfo to $NewComputerName”

}
else{
write-host “if the server number is over 240 you will have to enter them your self enjoy”
}

Pingback by The Linux Blog » 2010 Statistics

January 5, 2011 @ 6:32 am

[…] Posts of 2010 1) Shell Script To Get User Input 2) iPhone SSH Client 3) Using Cut Shellscript String Manipulation 4) rsync to smb share 5) […]

Comment by Lissa

October 1, 2012 @ 12:20 pm

Just wanted to leave a comment thanking you for this. I am a true beginner and the information you have provided has been very helpful.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>