0

I have a bash script where I want to set a case variable. For file1 there are two different NUMBER variables that I then I want to pass to a text file.

I have tried the following:

case $FILE in "file1") NUMBER="12";;& NUMBER="34";;& "file2") NUMBER="56";; esac mv textfile.txt $NUMBER.txt 

where I want the output for file1 to be the following:

12.txt 24.txt 

I am getting the following error:

syntax error near unexpected token `;;&' 

Do you have any suggestions? thanks so much.

2
  • 2
    It isn't even an issue of the case statement. You are giving one value to a variable and then overwriting it. What do you actually want to do here? Do you want to make two copies of the original textfile.txt, one named 12.txt and another named 24.txt? Commented Jun 24, 2022 at 15:41
  • yes! is there anyway to do this? Commented Jun 25, 2022 at 5:52

1 Answer 1

1

I'm afraid the logic of what you are trying to do won't work. You cannot assign two values to a variable, when you assign the second, the first is lost. This means that this would never do what you want:

number=1 ## $number is now 1 number=2 ## $number is now 2, and the original value 1 has been replaced. 

So, in order to make two copies of a file, you need to use a different approach.

Here are some ideas (note that I put your variable names in lower case: it's bad practice to use CAPS for shell script variable names since by convention, the global environment variables are capitalized, so this can lead to naming collisions and hard to debug issues):

  • Make one copy inside the case statement, the other afterwards:

    case $file in "file1") cp textfile.txt 23.txt number="34";; "file2") number="56";; esac mv textfile.txt $number.txt 
  • use an array instead

    case $file in "file1") numbers+=(23 34);; "file2") numbers+=(56);; esac for number in "${numbers[@]}"; do cp textfile.txt "$number".txt done rm textfile.txt 

    One drawback with this approach is that it does everything by copying instead of moving so it will be slightly slower since the first approach has at least one mv operation. You can't have more than one mv, but at least you can modify this so it makes one mv and so is as fast as the first approach:

    case $file in "file1") numbers+=(23 34);; "file2") numbers+=(56);; esac ## Iterate over all except the first element of the array for number in "${numbers[@]:1}"; do cp textfile.txt "$number".txt done ## move the file using the first number in the array mv textfile.txt "${numbers[0]}".txt 
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.