Basic for-loops -fixed

chriswelborn 0 Tallied Votes 298 Views Share

I'm no pro when it comes to BASH, but I have been known to shell-script my way out of a problem here and there. One of the useful things you can do is a for-loop, whether it be used on file names, script arguments, or just a string of words. Here are some very basic examples on how to do for-loops in BASH.

Edit: Fixed per Watael's suggestions.

#!/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."

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.