Monthly Archives: October 2013

Bash tits and bits

Command Substitutions:

list=`ls`

list=$(ls)

# below will assign to an array, you can use ${list[1]} to access individual element.

list=( * )


Variable assignment before command in one line

foo=bar ls $foo


Run bash in debugging mode

#!/bin/bash –x

or you can do

set –x # to turn on debugging in the script

set  +x # to turn off debugging


if COMMANDS; then COMMANDS; else COMMANDS; fi;

This can help you understand that if, then, else, fi are all kewords.

 

Another form:

if [[ $a == “good” ]]

Here [[ is a command.

A note from http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_02.html


[] vs. [[]]

Contrary to [, [[ prevents word splitting of variable values. So, if VAR="var with spaces", you do not need to double quote $VAR in a test – even though using quotes remains a good habit. Also, [[ prevents pathname expansion, so literal strings with wildcards do not try to expand to filenames. Using[[, == and != interpret strings to the right as shell glob patterns to be matched against the value to the left, for instance: [[ "value" == val* ]].


Ryan@Foundation ~
$ [ 1 -eq 1 ];

Ryan@Foundation ~
$ echo $?
0

Ryan@Foundation ~
$ [ 1 -eq 0 ];

Ryan@Foundation ~
$ echo $?
1

Ryan@Foundation ~
$ [ 1 -eq 1 ]

Ryan@Foundation ~
$ echo $?
0

Ryan@Foundation ~
$ [ 1 -eq 0 ]

Ryan@Foundation ~
$ echo $?
1

Ryan@Foundation ~
$