Bash basics: Difference between revisions

From Bitpost wiki
No edit summary
No edit summary
Line 1: Line 1:
Bash certainly has its set of snafus.
Bash certainly has its set of snafus.


* To store commands in variables:
=== store commands in variables ===
<pre># NOTE don't put spaces around equals sign!
<pre># NOTE don't put spaces around equals sign!
# NOTE don't use ampersands within command strings, they won't work
# NOTE don't use ampersands within command strings, they won't work
Line 13: Line 13:
$mycmd1 && $mycmd2 && $mycmd3
$mycmd1 && $mycmd2 && $mycmd3
</pre>
</pre>
* To capture output
=== capture output ===
<pre>myout=`program1 param`;</pre>
<pre>myout=`program1 param`;</pre>
* Note the difference a single quote makes to output...
* Note the difference a single quote makes to output...
Line 21: Line 21:
abc  def
abc  def
</pre>
</pre>
* To check for an error
=== check for an error ===
<pre>mkdir "$d2"
<pre>mkdir "$d2"
if [ $? -gt 0 ]; then
if [ $? -gt 0 ]; then
Line 28: Line 28:
fi
fi
</pre>
</pre>
* To read input from user
=== read input from user ===
<pre>echo "Create the subdirectory?  [$d2]"
<pre>echo "Create the subdirectory?  [$d2]"
if read answer; then
if read answer; then
Line 38: Line 38:
fi</pre>
fi</pre>


[http://www.panix.com/~elflord/unix/grep.html grep powerful options]
=== [http://www.panix.com/~elflord/unix/grep.html powerful grep options] ===

Revision as of 13:43, 7 July 2017

Bash certainly has its set of snafus.

store commands in variables

# NOTE don't put spaces around equals sign!
# NOTE don't use ampersands within command strings, they won't work
# use a blank command if needed, that's fine
mycmd1="command param param"
mycmd2="cmd2 param"
if [ -e /myspecialplace ]
mycmd2=""
fi
mycmd3="cmd3 param"
$mycmd1 && $mycmd2 && $mycmd3

capture output

myout=`program1 param`;
  • Note the difference a single quote makes to output...
$ eval echo "abc   def"
abc def
$ eval 'echo "abc   def"'
abc   def

check for an error

mkdir "$d2"
if [ $? -gt 0 ]; then
   echo "mkdir error, try that again..."
   exit 3
fi

read input from user

echo "Create the subdirectory?  [$d2]"
if read answer; then
    if [ ${answer} = "y" ] || [ ${answer} = "yes" ]; then
        {whatever}
    else
        {whatever}
    fi
fi

powerful grep options