Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
scripting:newbie_traps [2015/08/02 07:12]
bill_thomson
scripting:newbie_traps [2016/05/11 15:19] (current)
stephenwb Added section about return value vs. output
Line 14: Line 14:
   * no shebang   * no shebang
     * the interpreter used depends on the OS implementation and current shell     * the interpreter used depends on the OS implementation and current shell
-    * **can** be run by calling bash withthe ​script name as an argument, e.g. ''​bash myscript''​+    * **can** be run by calling bash with the script name as an argument, e.g. ''​bash myscript''​
   * ''#​!/​bin/​sh''​ shebang   * ''#​!/​bin/​sh''​ shebang
     * depends on what ''/​bin/​sh''​ actually is, for a Bash it means compatiblity mode, **not** native mode     * depends on what ''/​bin/​sh''​ actually is, for a Bash it means compatiblity mode, **not** native mode
Line 26: Line 26:
 Give it another name. The executable ''​test''​ already exists. Give it another name. The executable ''​test''​ already exists.
  
-In Bash it's a builtin, with other shells it might be an executable file - either ​way, it's bad name choice!+In Bash it's a builtin. With other shellsit might be an executable file. Either ​way, it's bad name choice!
  
 Workaround: You can call it using the pathname: Workaround: You can call it using the pathname:
Line 207: Line 207:
 See also: See also:
   * [[scripting:​basics#​exit_codes | Exit codes]]   * [[scripting:​basics#​exit_codes | Exit codes]]
 +
 +==== Output vs. Return Value ====
 +
 +It's important to remember the different ways to run a child command, and whether you want the output, the return value, or neither.
 +
 +When you want to run a command (or a pipeline) and save (or print) the **output**, whether as a string or an array, you use Bash's ''​$(command)''​ syntax:
 +<​code>​
 +$(ls -l /tmp)
 +newvariable=$(printf "​foo"​)
 +</​code>​
 +
 +When you want to use the **return value** of a command, just use the command, or add ( ) to run a command or pipeline in a subshell:
 +<​code>​
 +if grep someuser /etc/passwd ; then
 +    # do something
 +fi
 +
 +if ( w | grep someuser | grep sqlplus ) ; then
 +    # someuser is logged in and running sqlplus
 +fi
 +</​code>​
 +
 +Make sure you're using the form you intended:
 +<​code>​
 +# WRONG!
 +if $(grep ERROR /​var/​log/​messages) ; then
 +    # send alerts
 +fi
 +</​code>​
 +
 +Please see:
 +  * [[syntax:​ccmd:​intro]]
 +  * [[syntax:​expansion:​cmdsubst]]
 +  * [[syntax:​ccmd:​grouping_subshell]]