#!/bin/bash

# Demo for using for-loops.
printf "%s\n" "Here are some basic loops with arrays, strings, file names/dirs, and arguments."

# Array of strings
printf "\n%s\n" "Array of strings:"
myvalues=("value1 with spaces" "value2" "value3")
for value in "${myvalues[@]}"
do
    echo "    value: "$value
done

# String with spaces in it.
printf "\n%s\n" "String with spaces:"
myvalues2="my short string"
for value in $myvalues2
do
    echo "    test: "$value
done

# All files/directories in directory
printf "\n%s\n" "All Files/Directories:"
for filename in *
do
    if [ -f "$filename" ]; then
        echo "    found file: "$filename
    elif [ -d "$filename" ]; then
        echo "    found dir: "$filename
    else
        echo "    found other: "$filename
    fi
done

# All shell scripts in current directory
printf "\n%s\n" "All shell scripts:"
for shellscript in *.sh
do
    echo "    found shell script: "$shellscript
done

# arguments
if [ -z "$1" ]; then
    printf "\n%s\n" "You didn't pass any arguments, pass some for this test."
else
    printf "\n%s\n" "Arguments passed:"
    for argument
    do
        echo "    argument: "$argument
    done
fi

printf "\n%s\n" "Finished."
1
Contributor
1
Reply
17
Views
3 Years
Discussion Span
Last Post by chriswelborn
0

I forgot the C-Style for-loop, it could also come in handy.

maximum_number=10
for (( i = 0; i < maximum_number; i++ ))
do
    echo $i
done
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.