Skip to content

.-

Bash

Bash File Testing

-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable

Bash Shell CGI (yolinux.com)

Quick Tests in Scripts

If you need to test something and have a single action taken then you can avoid doing a bunch of if statements by doing a single line test. You can use the above tests to change what you're looking for.

[[ -f /file/path/here ]] || touch /file/path/here
[[ -d /dir/path/here ]] || mkdir -p /dir/path/here
[[ -L /link/path/here ]] || ln -s /file/path/here /link/path/here

These examples will take no action if true, so if they exist nothing happens. When they're false it will take the action on the other side of ||. You can do the inverse of it too by added a not (!) into in front of the test

[[ ! -f /file/path/here ]] || rm -f /file/path/here

So in this example if the file doesn't exist then it is true and nothing happens, otherwise the file is deleted if it does exist.

Functions

Bash (shell) functions are denoted by a keyword, () and {}. In the example below we have 3 functions, with the 4th function calling the other 3… and yes read into that what you will…

there() {
    echo "THERE -"
}
are() {
    echo "ARE -"
}
four() {
    echo "FOUR LIGHTS"
}
picard-says() {
    there
    are
    four
}

echo "Picard says:"
picard-says # This runs the function picard-says, which runs the others

Template

Here's a quick template to get your started

#!/bin/bash

########################
# COMMENTS/INFO/ETC
########################

# Variables Go Here

foo=bar

# PREP / PRE TASKS 

cd "$HOME" || exit 1

# FUNCTIONS GO HERE

one() {
    echo "Function one"
}

# MAIN
one