0

I am new to shell scripting, and need to output a series of commands to a local variable in a shell script, but keep on failing. For instance, the output of grep -c to a variable that will be use in an if statement. If anyone can redirect me over to a source that explains the process, I will appreciate.

#!/bash/sh

myVar = ls ~/bin | grep -c $0
mklement0
  • 382,024
  • 64
  • 607
  • 775
Jose Gonzalez
  • 49
  • 1
  • 7
  • You can use `backticks`: myVar = \`ls ~/bin | grep -c $0\` – Bartez Mar 25 '17 at 18:41
  • Indeed, flagged as duplicate. – Montmons Mar 27 '17 at 15:35
  • 1
    @Bartez: It's [better to use modern command-substitution syntax `$(...)` instead of legacy syntax `\`...\``](http://mywiki.wooledge.org/BashFAQ/082); also note that your command still has spaces around the `=` sign. – mklement0 Mar 27 '17 at 15:44
  • 1
    @mklement0, one of the beautiful things about the editable dupe-list support is that we can close a question with *multiple* duplicates, if it's simply a composite of errors for which we already have questions with answers available. And frankly, if a question has more than one underlying problem, I'd argue that that's an argument in favor of eligibility for close-as-overbroad more than it is a saving grace. – Charles Duffy Mar 27 '17 at 15:51
  • @CharlesDuffy: Makes sense - didn't even know that specifying multiple duplicates is an option. – mklement0 Mar 27 '17 at 16:00
  • That's a fairly new change -- as long as you have a dupehammer in one of the relevant tags, see the "edit" button next to "This question already has an answer here:", which will take you to an interface where you can modify the dupe list. – Charles Duffy Mar 27 '17 at 16:03

1 Answers1

4

Posting your code at shellcheck.net gives you valuable pointers quickly:

myVar = ls ~/bin | grep -c $0
^-- SC2037: To assign the output of a command, use var=$(cmd) .
      ^-- SC1068: Don't put spaces around the = in assignments.
                           ^-- SC2086: Double quote to prevent globbing and word splitting.

If we implement these pointers:

myVar=$(ls ~/bin | grep -c "$0")

Also note that your shebang line has an incorrect path - the #! must be followed by the full path to the executing shell's binary.

Resources for learning bash, the most widely used POSIX-compatible shell:

mklement0
  • 382,024
  • 64
  • 607
  • 775