Taco Steemers

A personal blog.
☼ / ☾

Notes on bash

" Bash is the GNU Project's shell—the Bourne Again SHell ."

Using a variable in a string

There can not be any space between the variable name, the equals sign and the value.

MY_VAR="test"
echo "$MY_VAR"

Capturing the output of a command in a variable

Using the dirname command, should print only a period (".").

echo "$(dirname "$0")"

Script name, directory, present working directory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash

echo "Script name:"
echo "$BASH_SOURCE"
echo "$0"

echo "Directory that contains the currently running script, relative to PWD:"
echo "$(dirname $BASH_SOURCE)"
echo "$(dirname "$0")"
echo "${0%/*}"

echo "Present working directory: $PWD"

Includes the ./ when we call the script like ./my_script , but not when calling as sh my_script .

See this stackoverflow post . See also this stackoverflow post .

If/else, comparing strings

String comparison can be done using == and !=, as in most programming languages.

if [[ "$TITLES_ORIGINAL" != "$TITLES_NEW" ]]; then
    // ...
fi

If/else, checking if a directory exists, making a directory

if [ ! -d "$DL_DIRECTORY" ]; then
    mkdir "$DL_DIRECTORY";
else
    rm $RSS_ORIGINAL_FILE_PATH 2> /dev/null
fi

Redirecting output

We can discard output by redirecting it to the null device.

Standard output is redirected with 1> .

Error-related output is redirected with 2> .

We can redirect both by using &> .

ls -al 1> /dev/null
my_script.sh &> /dev/null