user11104582
user11104582

Reputation:

What about this causes the syntax error? ('near &&')

A set of commands stringed together with "&&" doesn't work when aliased, works when entered directly.

I have a set of eleven commands for initializing Git, creating a new repo, creating some config files, and creating several branches.

I've combined these into single command stringed by &&s for convenience. This command works when pasted directly. It fails when I run an aliased version.

I've edited my ~/.bashrc file to the following code:


alias repo='git init && hub create && echo "/node_modules" >.gitignore && tsc --init && git add -A && git commit -S -m "First commit" && git push -u origin master && git checkout -b dev && git push origin head && git checkout -b new_feature && git push origin head'

I've tried moving it to its own function:

createRepo () {
  git init 
  && hub create 
  && echo "/node_modules" >.gitignore 
  && tsc --init 
  && git add -A 
  && git commit -S -m "First commit"  
  && git push -u origin master  
  && git checkout -b dev 
  && git push origin head 
  && git checkout -b new_feature 
  && git push origin head
}

alias repo="createRepo"

And it gives the exact same result.

To be clear, pasting git init && hub create && echo "/node_modules" >.gitignore && tsc --init && git add -A && git commit -S -m "First commit" && git push -u origin master && git checkout -b dev && git push origin head && git checkout -b new_feature && git push origin head directly causes it to work as functioned.

It's only when I attempt to alias it that I get the syntax error.

I'm using nano

I expect repo in Bash it to:

  1. Initialize a git repo
  2. Create a GitHub repo
  3. Add, commit, and push the master branch
  4. Create, checkout, and push a dev and new-feature branch

Actual: bash: syntax error near &&

Upvotes: 0

Views: 1520

Answers (2)

glenn jackman
glenn jackman

Reputation: 246774

bash doesn't know that the command continues on to the next line unless:

  • you use a line continuation

    createRepo () {
      git init \
      && hub create \
      && echo "/node_modules" >.gitignore \
      && ...
    
  • you put the && at the end of the line

    createRepo () {
      git init &&
      hub create &&
      echo "/node_modules" >.gitignore &&
      ...
    

Upvotes: 2

user11104582
user11104582

Reputation:

Bash loads the ~/.bashrc file once at the start, so I had to restart Bash entirely.

My repo alias worked after that.

Upvotes: 0

Related Questions