简体   繁体   中英

Getting "[: =: unary operator expected" in a bash program

I've been working on a sample bash program to practice bash scripting, but whenever I try to run it with the correct variables, it outputs "[: =: unary operator expected" and quits.

#! /bin/bash
clear
i=""
P="PASSWORD"
echo "Please enter your password"
while [ $i = "PASSWORD" ]
do
read $i
done

if $i is empty, you got syntax error because of not enough arguments [ = "PASSWORD" ]

  1. you can use bash option [[ $i = "PASSWORD" ]] But it is bash operator, and it could be not compatible with old shells

  2. you can put your variable in quotas, like [ "$i" = "PASSWORD" ] This is preferred thing, you also will fix an issue, if your variable contains spaces or shell expansion marks like *, ?, [1..9]

but whenever I try to run it with the correct variables, it outputs "[: =: unary operator expected" and quits.

That's because you have an unquoted/empty variable inside the [ , either quote your variables or use [[ which is safer and more robust.

while [ $i = "PASSWORD" ]

The value of $i is empty there is no way a user can give the value/input, so it will fail


Edit: As mentioned by @William Pursell , Regardless which test you are using, it still has some pitfall, the lesson here is to sanitize/validate the input, eg test it if it is indeed a digit, if it is not empty and so on.


Try this, It might do what you wanted.

#!/usr/bin/env bash

clear
p="PASSWORD"
read -rp "Please enter your password: " input  ##: Ask the user to enter the password

until [[ $p == "$input" ]]; do ##: The loop will continue until both vars matches
  clear
  printf 'Please try again! %s does not match..\n' >&2 "$input"
  read -rp "Please enter your password: " input
done

##: If it matches print a message and the value of input
printf '%s is a match!\n' "$input" 

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