bash_scripting

Differences

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

Link to this comparison view

Next revision
Previous revision
bash_scripting [2017/04/25 15:09] – created mguptonbash_scripting [2017/07/11 19:21] (current) mgupton
Line 1: Line 1:
 ======Bash Scripting====== ======Bash Scripting======
 ======Conditionals====== ======Conditionals======
-  * The ''?'' variable has the exit/return value of the last program that ran.+  * The special variable ''$?'' has the exit/return value of the last program/command that ran.
  
 <code bash> <code bash>
 if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
-  echo "All is well." +    echo "All is well." 
-  exit 0+    exit 0
 elif [ $? -eq 1 ]; then  elif [ $? -eq 1 ]; then 
-  echo "Doh!" +    echo "Doh!" 
-  exit 1+    exit 1
 else else
- echo "Really?!" +   echo "Really?!" 
- exit 2+   exit 2
 fi fi
 </code> </code>
Line 18: Line 18:
 ===One line if statement=== ===One line if statement===
 <code bash> <code bash>
-if [$? -eq 0]; then echo "Error"; else echo "OK"; fi+if [$? -eq 0]; then echo "OK"; else echo "Error"; fi
 </code> </code>
 +
 +======Iteration======
 +===for loop===
 +<code bash>
 +for i in alpha beta gamma
 +do
 +    printf "$i\n"
 +done
 +
 +a=alpha
 +b=beta
 +c=gamma
 +
 +for j in "$a" "$b" "$c"; do
 +    printf "$j\n"
 +done
 +</code>
 +
 +<code bash>
 +for i in $( ls ); do
 +  echo item: $i
 +done
 +
 +LIST="$(ls *.html)"
 +for i in "$LIST"; do
 +   echo $1
 +done
 +</code>
 +
 +===while loop===
 +<code bash>
 +COUNTER=0
 +
 +while [  $COUNTER -lt 10 ]; do
 +  echo The counter is $COUNTER
 +  let COUNTER=COUNTER+1 
 +done
 +</code>
 +
 +======Command Substitution/Interpolation======
 +  * Command substitution will run the specified command and replace the command with the output from the command in the location where it is specified as part of input to some other command.
 +<code>
 +$(<command expression>)
 +</code>
 +<code>
 +text=$(cat alpha.txt)
 +</code>
 +<code>
 +`<command expression>`
 +</code>
 +
 +======File Manipulation======
 +==Delete a file if it exists.==
 +<code bash>
 +[[ -f "$file" ]] && rm -f "$file"
 +</code>
 +
 +======File I/O======
 +
 +===Read a text file line by line.===
 +<code bash>
 +#!/bin/bash
 +while read line
 +do
 +    name=$line
 +    echo "Text read from file - $name"
 +done < $1
 +</code>
 +
 +===Read each line of a file as a CSV record.===
 +<code bash>
 +while IFS=, read col1 col2
 +do
 +    echo "I got:$col1|$col2"
 +done < myfile.csv
 +</code>
 +
 +======Resources======
 +  * [[http://wiki.bash-hackers.org/|The Bash Hackers Wiki]]
 +
  • bash_scripting.1493132947.txt.gz
  • Last modified: 2017/04/25 15:09
  • by mgupton