2
#!/bin/bash

echo "Please enter your desired file type(s) from the following list

gif jpg docx

any other value than these three is also valid"

read entry1 entry2 entry3 entry4

echo your first choice was: $entry1
echo your second choice was: $entry2
echo your third choice was: $entry3
echo your fourth choice was: $entry4


if [$entry1 || $entry2 || $entry3 || $entry4 =="jpg"]

then

mkdir jpg

echo "jpg directory created"

fi

What I am trying to do is, create a directory whenever a chosen value is entered. If jpg, gif or docx is typed: a directory is created for jpg, gif or docx as appropriate. At present, no matter what I enter into my code, I am ALWAYS creating a jpg directory.....even when I enter jpg, gif, docx or some utterly random value such as tinzebra.

My understanding was that the statement after the THEN was contingent upon the statement being true/false as the case maybe, but it would appear that my code is interpreting the Boolean as always true....which is confusing me immensely

1
  • 4
    Copy paste your script in shellcheck.net and fix the errors shown Commented Nov 8, 2017 at 13:17

2 Answers 2

3

So, I think your problem is in your conditional.

The line:

if [$entry1 || $entry2 || $entry3 || $entry4 =="jpg"]

Is really saying, if $entry1 is set, or $entry2 is set, or $entry3 is set, or $entry4 is equal to "jpg".

If you're only trying to create a directory when one of them is set to jpg, try modifying the line to this:

if [ "$entry1" = "jpg" ] || [ "$entry2" = "jpg" ] || [ "$entry3" = "jpg" ] || [ "$entry4" = "jpg" ]

That way you're checking if entries 1, 2, 3, or 4 is "jpg", create the "jpg" directory.

Sign up to request clarification or add additional context in comments.

3 Comments

You have the right idea, but your syntax is woefully wrong.
@chepner to whom was that addressed to?
@chepner Thanks for the catch. I simply copied and pasted the OP's code.
1

Your idea is right but the syntax for the conditionals and rest of the script can be improved a great deal. You could just read n variables simply using a loop construct using for or while

declare -i input_count
input_count=4
for ((i=1; i<=input_count; i++)); do 
    var="entry_$i"
    read -p "Choose between (gif|jpg|docx) for $var: " "$var" 
done

Now that we have the variables stored/read you need to make the check again using a loop and create a directory if does not exist already using the -p switch.

for ((i=1; i<=input_count; i++)); do 
    var="entry_$i"
    if [[ "${!var}" =~ ^(gif|jpg|docx)$ ]]; then
        mkdir -p "${!var}" || { printf 'error creating dir\n' >&2; exit 1; }
    fi
done

The above code uses the niceties of bash which you can run with specifying the interpreter as #!/usr/bin/env bash at the top of the script.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.