Bash shell script error sh: [: missing `] '

Purpose:

I am trying to create a useful shortcut to initialize a git repository locally and at the same time creating a remote repo source on a bitpack or github. This function is added to my file .bashrcin my home directory.

Here is the bash function (which gives the error):

function initg() {
 # Defaults to bitbucket API
 local API="https://api.bitbucket.org/1.0/repositories/"
 local DATA="name=$3&description=$4&is_private=true&scm=git"
 local REMOTE="ssh://git@bitbucket.org/$2/$3"

 # Use github if specified
 if [ "$1" == "gh" ]; then
      API="https://api.github.com/user/repos"
      DATA='{"name":"$3", "description": "$4"}'
      REMOTE="git@github.com:$2/$3"
 fi

 if [ -z "$API" ] || [ -z "$DATA" ] || [ -z "$REMOTE" ] || [ -z "$2" ]
 then
      echo "A parameter is missing or incorrect"
 else
      curl -X POST -u $2 ${API} -d ${DATA}
      git init
      git add .
      git commit -m "Created repo"
      git remote add origin $REMOTE
      git push -u origin master
 fi
}

Error:

username@COMPUTER-NAME /path/to/local/repo
$ initg gh username bash_test desc
sh: [: missing `]'
sh: [: missing `]'
Enter host password for user 'username':

My question is:

First, where is my mistake? Secondly, how can I improve the control flow or structure of this script to achieve the stated goals?

+5
source share
4 answers

I have such an error because I have not used a space before] ex:

if [ "$#" -ne 2]; then

instead

if [ "$#" -ne 2 ]; then

PS: I know this is an old question, but it can help someone :)

+5
source

Update / Preliminary Response

, , , () , .

script , bash -x test.sh, devnull .

. , .

username@COMPUTERNAME /d/test
$ bash -x test.sh
+ initg gh username bash_test desc
+ local API=https://api.bitbucket.org/1.0/repositories/
+ local 'DATA=name=bash_test&description=desc&is_private=true&scm=git'
+ local REMOTE=ssh://git@bitbucket.org/username/bash_test
+ '[' gh == gh ']'
+ API=https://api.github.com/user/repos
+ DATA='{"name":"$3", "description": "$4"}'
+ REMOTE=git@github.com:username/bash_test
+ '[' -z https://api.github.com/user/repos ']'
+ '[' -z '{"name":"$3", "description": "$4"}' ']'
+ '[' -z git@github.com:username/bash_test ']'
+ '[' -z username ']'
+ curl -X POST -u username https://api.github.com/user/repos -d '{"name":"$3",' '"description":' '"$4"}'
+ Enter host password for user 'username':

:

, , , (), DATA. -, , script, $3 $4, .

DATA='{"name":"$3", "description": "$4"}'

, , , .

, [[ ]] , ${3}, DATA ( ):

DATA="{\"name\":\"${3}\",\"description\":\"${4}\"}"

script

, - , . , $DATA, curl, '{"name":"$3",' '"description":' '"$4"}'

+3

Several times I came across such nonsense from bash (an error?), And the output was replaced [ some-condition ]bytest some-condition

+3
source

To pass a variable DATA, try the following:

printf -vDATA '{"name":"%s", "description": "%s"}' $3 $4
echo "$DATA"
0
source

All Articles