Basic for-loops with strings, arrays, file names, and arguments.

chriswelborn 0 Tallied Votes 374 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.


printf "Here are some basic loops with arrays, strings, file names, and arguments.\n"

# Array of strings
printf "\nArray of strings:\n"
myvalues=("value1" "value2" "value3")
for value in ${myvalues[@]}
    echo "    value: "$value

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

# All files in directory
printf "\nAll Files:\n"
for filename in *
    echo "    found file: "$filename

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

# arguments
if [ -z "$1" ]; then
    printf "\nYou didn't pass any arguments, pass some for this test.\n"
    printf "\nArguments passed:\n"
    for argument in $@
        echo "    argument: "$argument

printf "\nFinished.\n"
Watael 4 Junior Poster


printf with an f, like format. it should be used to separate format from data.

Array of strings : use more quotes: "${array[@]}", in case element has space(s) in it.

All files and directories, in current directory.

Arguments, in @ is not needed : for i do :etc; done

thanks, i posted a 'fixed' version since I wasn't able to edit this one. hopefully someone will come along and delete this or it will get buried. I appreciate the suggestions, I fixed the printf to reflect what it's actually meant for, although I do still cheat some times with my personal scripts.

also, taken from man page examples:

Print text followed by variable $USER:
$ printf "Hello, $USER.\n\n"

so it can't be that bad to cheat...
although when using a variable I really would have done this:

$ printf "Hello, %s.\n\n" "$USER"
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.