0

I currently have a few files called file1.txt file2.txt file3.txt

I want to create a case statement to choose which to delete and I currently have:

files=" "
read number

case $number in
1) files=rm file1.txt ;;
2) files=rm file2.txt ;;
3) files=rm file3.txt ;;
*) files='this file does not exist' ;;
esac
echo $options

however whenever I try to run it it displays an error such as "file1.txt: command not found."

Can anybody explain what I'm doing wrong here?

A.Rae
  • 11
  • 1
  • 3
  • BTW, using a scalar variable named `files` to store (presumably) a *list* of files is bad juju. A scalar, by its nature, can store only one value; if you rely on being able to split that value on spaces to get a list of filenames, you'll be very disappointed when trying to work with files whose names contain spaces. – Charles Duffy Jan 05 '16 at 17:50
  • ...it's not clear to me, as a reader, why you have a `files` variable in your script at all. Why not just run the deletions directly? – Charles Duffy Jan 05 '16 at 17:55
  • The question I marked this as duplicative of isn't *quite* on-point in and of itself, but the accepted answer addresses the scenario directly. – Charles Duffy Jan 05 '16 at 17:58
  • Sorry I was just using the word files as an example, although I wasn't aware its a bad thing to do, I'll keep that in mind thank you :) – A.Rae Jan 05 '16 at 18:27

1 Answers1

0
files=rm file1.txt

...runs file1.txt as a command with the environment variable files set to the value rm.

This is generally true of any simple command preceded by KEY=VALUE pairs: Those pairs are treated as environment variables to be set only for the duration of that one command.


Perhaps you instead want:

files=file1.txt

...or:

files=( ) # create an empty array, not a scalar (string) variable.
read number
case $number in
  1) files+=( file1.txt ) ;;  # or simply: 1) rm file1.txt ;;
  2) files+=( file2.txt ) ;;  # or simply: 2) rm file2.txt ;;
  3) files+=( file3.txt ) ;;  # or simply: 3) rm file3.txt ;;
  *) echo "This file does not exist" >&2 ; exit 1;;
esac

# ...if collecting filenames in an array, then...
echo "Removing files:" >&2
printf '  %q\n' "${files[@]}" >&2     # ...expand that array like so.

rm -f "${files[@]}" # likewise

To understand why something like cmd='rm file1.txt' would be -- while correct syntax -- very poor practice and opening yourself up to bugs, see BashFAQ #50.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Your option to just put it as 1) rm file1.txt etc, works perfectly, thank you very much! – A.Rae Jan 05 '16 at 18:29