Adam Richardson's Site

Bash Notes

Table of Contents

<2022-05-01 Sun>

Functions

  • The function syntax is similar to C but arguments and return types are not specified
example_function () {
    echo "Function Begin"
    ls -l
    echo "Function End"
}
  • To reference an argument use $NUM starting at 1
example_function () {
    echo "Argument: $1"
}

example_function "Ohh yeah"
  • To return a value use the return command
  • To access the return value of the previous run function use $?
example_function () {
    return 100
}

example_function
echo $?

For Loop

for (( i=0; i<=10; i++ ))
do
    echo $i
done

Looping over Arrays

arr=(abc def ghi jkl)
for x in "${arr[@]}"
do
    echo $x
done

Check If File Exists

if [ -f foo.txt ];
then
    echo "foo.txt exists"
else
    echo "foo.txt does not exist"
fi
  • The -f flag checks for a file
  • The -d flag checks for a directory
  • The -e flag checks for either files or directories