Bash_script - Anton-L-GitHub/Learning GitHub Wiki

General

Tips

  • Always use absolute paths in scripts.
  • Save script in $HOME/bin - (only for you) or /usr/local/bin (for everyone on the computer).
  • $? - Exit code from last script.

Comments

# One-line comment
: '
Multi-line comment
'

Variables

name="Pelle"

Arguments from Command Line

echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
echo "Array of all arguments = $@"

HereDoc

echo << _EOF_
blabla balbal
_EOF_

Concatinate strings

fNamn="Peter"
lNamn="Pan"
fullName="$fNamn $lNamn"
fullName+=" är bäst!"

Substrings

str="Hej jag heter Peter Pan och jag bor i Göteborg"
name=${str:13:10}
# ${var:where:howMany}

Math

x=5
y=3
((sum = x + y))

Conditionals

IF Statements

if [ "$name" == "Brad" ]; then
    echo "Your name is Brad!"
elif [ "$name" == "Jack" ]
    echo "Your name is Jack"
else
    echo "Your name is not Brad or Jack!"
fi

File Conditions

ex.

if [ -e "/path/to/file" ]; then
  • -d - True if directory.
  • -e - True if exists.
  • -f - True if a file.
  • -g - True if group id is set on file.
  • -r - True if readable
  • -s - True if file has non-zero size
  • -u - True if user-ID is set on file.
  • -w - True if writable.
  • -x - True if executable.

Case Statements

echo -n "Enter a number:"
read number

case "$number" in
"1")
    echo "You won!" ;;
"2" | "3")
    echo "You get a prize" ;;
*)
    echo "Sorry, try again! " ;;
esac

Loops

While

while [ condition ]; do
    # body
done

For

for item in {a..z}; do
    echo "$item"
done

For - ( C Style )

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

Functions

function greet_user() {
    local mood="happy"
    echo "Hello $USER you're $mood"
}
greet_user

Parameters $1, $2 osv..

Nice examples

Read file

file=$1
while read line; do
    echo $line
done < $file

Forloop CSV

IFS=","
animals="man,bear,pig,dog,cat,sheep"

for animal in $animals; do
    echo "$animal"
done

Unlimited arguments

objects=$@

for object in $objects; do
    if [ -f "$object" ]; then
        echo "\"$object\" is a file!"
        ls -l $object

    elif [ -d "$object" ]; then
        echo "$object is a directory!"
        ls -l "$object"

    else
        echo ls -l "$object"
    fi
done