You likely want to do something like the following:
#!/bin/sh
printf 'Enter name: ' >&2
read -r name
case $name in
ace)
run ace.txt
;;
com)
run commscope.txt
;;
ros)
run rosgenberger.txt
;;
*)
printf 'No match for "%s"\n' "$name"
esac
This reads a "name" from the user and executes a command based on the user's response.
In the bash
shell, you could use something a bit slimmer:
#!/bin/bash
declare -A map=(
[ace]=ace.txt
[com]=commscope.txt
[ros]=rosgenberger.txt
)
read -p 'Enter name: ' -r name
if [[ -n ${map[$name]} ]]; then
run "${map[$name]}"
else
printf 'No match for "%s"\n' "$name"
fi
This sets up an associative array with the expected "names" as keys and the corresponding filenames as values. Depending on the user's input, the correct filename is used with the run
command.
Most of the time, though, you don't want to interact with the user, but to allow the user to simply provide the input via a command line option. The following bypasses the interactive prompt for input by using the first argument passed via the command line as the default value for name
:
#!/bin/bash
name=$1
declare -A map=(
[ace]=ace.txt
[com]=commscope.txt
[ros]=rosgenberger.txt
)
if [[ -z $name ]]; then
read -p 'Enter name: ' -r name
fi
if [[ -n ${map[$name]} ]]; then
run "${map[$name]}"
else
printf 'No match for "%s"\n' "$name"
fi
This would be used like this:
./myscript ace
... for example. The script would then bypass the interactive question and execute run ace.txt
.
The code could be slimmed down further by letting variable expansion needed for the run
command do our error reporting:
#!/bin/bash
name=$1
declare -A map=(
[ace]=ace.txt
[com]=commscope.txt
[ros]=rosgenberger.txt
)
if [[ -z $name ]]; then
read -p 'Enter name: ' -r name
fi
run "${map[$name]?Name $name not matched}"
This would output something like
line 15: map[$name]: Name Boo not matched
if the user entered the name Boo
.
$name = readinput(Enter name:)
instruction certainly looks wrong for most shells I know (space around=
, command name instead of command substitution ...). I would recommend usingshellcheck
to debug your script; the tool is also available standalone on many Linux distributions. Also, please indicate exactly how the "script is not getting executed": is there an error message, or simply unexpected behavior? If so, which? Please edit your question to address these points, don't reply using comments. – AdminBee Jan 06 '21 at 08:47