Specify an entire UNIX command as a command line argument

I'm trying to write a bash script called YN that looks like the following

YN "Specify a question" "doThis" "doThat"

where "doThis" will be executed if the answer is "y", otherwise "doThat".

For example

YN "Do you want to list the file dog?" "ls -al dog"  ""

Here's my attempt at the script YN

#!/bin/bash
echo "$1"
read Answer;
if [ "$Answer" = "y" ] ; then
    . "$2"
else
    . "$3"
fi

If I run the above example it returns

ls -al dog: No such file or directory

Could anybody advise please?

#!/bin/bash

echo -n $1

read ANSWER

if [ "$ANSWER" = "y" -o "$ANSWER" = "Y" ]
then
      $2
else
      $3
fi

you can try executing it in ,
YN "Do you want to list the file dog?" "ls -al dog" ""

The file dog should be in current directory, or else mention the path.
Thanku :slight_smile:

Note that things like variables, wildcards, and backticks won't be expanded inside the command. This is a security feature to prevent people from doing horrible things just by accidentally misusing a variable.

Why not try something like this for you YN script:

ans=""
while [ -z "$ans" ]
do
    printf "%s" "$1"
    read ans
    case $ans in
        y|Y) true;;
        n|N) false;;
        *)   tput cuu1
             ans="";;
    esac
done

You can then use the if statement to deal with both answers.
Note you can also nest questions and it all looks pretty neat:

if YN "Do you want to list the file dog? "
then
    ls -al dog
else
    if YN "How about the file cat then? "
    then
        ls -al cat
    fi
fi

---------- Post updated 21-02-13 at 06:25 AM ---------- Previous update was 20-02-13 at 06:56 AM ----------

Also, if you have a single action you can combine use && like this:

YN "Do you want to list the file dog? " && ls -al dog

or use || if action is for negative response.