简体   繁体   中英

Simple Bash Script Not Working

I'm having issues with a shell script I'm working on that for whatever reason is not working as intended. The bulk of the script, and where things are going wrong, is below:

for username in $list
do
   sleep $sleep
   VAL=`curl -H 'Client-ID: $clientid' -s $host$username | jq -r .message | grep -E "unavailable|not found"`
   if [[ $VAL == *"not found"* ]]; then
     echo "$username is available"
     echo "$username" >> available.names
   else
     echo -e "$username is reserved"
   fi
done

I realize there are some variables such as sleep , host , clientid , and username but to give you an idea of what I'm working with, the result of the curl command ran at the VAL line (minus the grep) would be something like this:

User "username" was not found
or
User "username" is unavailable

So including the pipe to grep -E , the result of VAL would simply be something like:

not found

Now according to this StackOverflow answer , I should be able to wildcards so that, when using my script, if the VAL contains "not found" then it should echo that the username is available. As I've done here:

[[ $VAL == *"not found"* ]]

However what it's doing is the else statement for all usernames that are being checked. So even ones where the VAL contains "not found", it's still echoing that the username is taken.

Does anyone see anything wrong with my script that would cause this to happen? I've looked it over about 100 times and I'm getting no errors to help troubleshoot, only that it's not working as intended. Any help would be appreciated.

The single-quote in -H 'Client-ID: $clientid' is clearly wrong, as the value of $clientid is not expanded that way. Use double-quotes instead.

And btw you don't need [[ $VAL == *"not found"* ]] , you can write a conditional directly using the exit code of grep of the pipeline:

for username in $list
do
   sleep $sleep
   if curl -H "Client-ID: $clientid" -s "$host$username" | jq -r .message | grep -qE "unavailable|not found"; then
     echo "$username is available"
     echo "$username" >> available.names
   else
     echo "$username is reserved"
   fi
done

As @CharlesDuffy pointed out in a comment, the echo -e made no sense, so I removed that too. He also pointed out the code smell in writing for username in $list , instead of using proper arrays. ( list=( allison bob charlie ); for username in "${list[@]}"; do ... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM