2

So I'm creating a function that does a for loop in all the files in a directory as a given argument and prints out all the files and directories:

#!/bin/bash

List () {
    for item in $1
            do
            echo "$item"
            done
}

List ~/*

However when I run the script it only prints out the first file in the directory.

Any ideas?

3

If you're trying to iterate over files in a directory you need to glob the directory like so:

#!/bin/bash

List () {
    for item in "${1}/"*
            do
            echo "$item"
    done
}

Then call it like:

$ list ~

Alternatively, if you want to pass multiple files as arguments you can write your for loop like this:

List () {
    for item
            do
            echo "$item"
    done
}

Which can then be called as:

$ list ~/*

What's wrong with your current function:

When you call it with a glob, it passes each file in the directory as a separate argument. Let's say your home directory contains file1, file2, and file3. When you call list ~/*, you are essentially calling:

list ~/file1 ~/file2 ~/file3

Then your for loop is only being passed positional parameter 1 so for item in ~/file1 and the other positional parameters are unused.

Also thanks Ilkkachu for pointing out that you also forgot a / in your hashbang, which I completely missed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.