Wifil
Wifil

Reputation: 41

writing a loop in Unix that reads user input yes or no

I am trying to write a program that will display the running processes and ask the user if they would like to kill each process. here is my code

#! /bin/bash

ps

PID TTY          TIME CMD
1681 pts/1    00:00:00 tcsh
1690 pts/1    00:00:00 bash
1708 pts/1    00:00:00 script
1710 pts/1    00:00:00 ps

ps | while read line; do

id=$(echo $line | cut -d' ' -f 1)
name=$(echo $line | cut -d' ' -f 4)

echo 'process ID: ' $id 'name: ' $name
echo -n 'Would you like to kill this process? Yes/No: '
read word < /dev/tty
if [$word == 'yes' ]; then
kill $id

fi

done

I have two issues..one is that when i type no I get an error line 10 [no: command not found. the second one is that when I am assigning the variables to id and name, it automatically reads the first line which gives me

process ID: name: cmd

Upvotes: 1

Views: 317

Answers (2)

Marc B
Marc B

Reputation: 360662

Your if is wrong:

if [ "$word" = "yes" ]
    ^^^^^^^^--note the space + quotes around the var.

As well, [ doesn't use == for equality testing. it's just =.

Upvotes: 1

rm-vanda
rm-vanda

Reputation: 3158

First of all, you shouldn't have to do the < /dev/tty part on that one line; read word is sufficient.

Secondly, you just need a space in your if clause, after the opening bracket - like so:

if [ $word == 'yes' ]; then

Upvotes: 0

Related Questions