Skip to content

Latest commit

 

History

History
84 lines (76 loc) · 2.13 KB

BashScripting.md

File metadata and controls

84 lines (76 loc) · 2.13 KB

String concetanation

var_hello="Hello,"
var_world=" World"
var_combo="$var_hello$var_world"
echo "$var_combo

Output results/errors of commands to a file

Write stdout to file

foo > stdout.txt

Write stderr to file

foo 2> stderr.txt

Write stdout and stderr to different files

foo> output.txt 2> stderr.txt

Wite stdout and stderr to the same file

foo > allout.txt 2>&1

If-Statements

i=0
if [ $i -ne 1 ]; then
   echo "i is not 1"
else
   echo "i is $i"
fi

Modify key/value pairs in config files

log_size=80
target_key="max_log_file"
config_file="/etc/audit/auditd.conf"
sed -c -i "s/\("$target_key" *= *\).*/\1$log_size/" $config_file

Variables and Subshells

The following bash snippet will change the variable 'i' in a while loop that runs in a subshell. This is beacuse the arguments are piped into the while loop.

i=0
find . -type f | while read line
do
   i=$(($i + 1))
   echo $i      # Will increase each iteration
done
echo $i         # Will NOT be increased

i will stay 1.
In order to reference to i you need to use a so-called Here-String as described here. The same code would look the following:

i=0
while read line
do
   i=$(($i + 1))
   echo $i      # Will increase each iteration
done <<< "$(find . -type f)"
echo $i         # Will be increased

i will be have the incremented value. On the other hand the following for loop will reference to i. This is because i is not passed into a subshell.

i=0
for file in $(find . -type f); do
  i=$(($i + 1))
  echo $i      # Will increase each iteration
done
echo $i

Shellcheck for script analysis tool

https://github.com/koalaman/shellcheck

Shellcheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.