Kim Stacks
Kim Stacks

Reputation: 10812

How to enforce no spaces in a bash script `read`?

This is my function in a bash script

function add_github_token_with_alias(){

  while [ -z $alias ]
  do
    echo -en "\n"
    read -p "An alias to name your token (or press Ctrl+C to cancel): " alias
  done

  while [ -z $token ]
  do
    echo -en "\n"
    read -p  "Token (or press Ctrl+C to cancel): " token
  done
}

When I run it, it looks like this

An alias to name your token (or press Ctrl+C to cancel): a new one
/opt/digitalocean/github_tokens_setup.sh: line 18: [: too many arguments

Token (or press Ctrl+C to cancel): abc

Is the information correct? [Y/n]

Is there a way I can block user from submitting spaces in their response? How should I write it?

Upvotes: 0

Views: 287

Answers (1)

Kim Stacks
Kim Stacks

Reputation: 10812

Thanks for @WilliamPursell comment, I know what to do

I added

if [[ "$alias" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset alias
fi

To do the checking of input as well as "$alias" in the while statement as per advised

function add_github_token_with_alias(){

  while [ -z "$alias" ]
  do
    echo "\n"
    read -p "An alias to name your token (or press Ctrl+C to cancel): " alias
    if [[ "$alias" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset alias
    fi
  done

  while [ -z "$token" ]
  do
    echo "\n"
    read -p  "Token (or press Ctrl+C to cancel): " token
    if [[ "$token" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset token
    fi
  done
}

Upvotes: 1

Related Questions