Tomala
Tomala

Reputation: 557

listing files from directory by passing command line arguments

I am trying to list files from any number of directories by using command line arguments. I am trying to pass the directory paths through the command line and display files that are in searched directories. Something like this. "Directory: PATH1" files files files

"Directory: PATH2" files files

etc.

So I am using $* to pass all of the command line arguments but it only displays files from the first listed directory.

#!/bin/bash


cd $*
for filename in *
do
        echo "Directory: $*"
        echo $filename
done

Upvotes: 0

Views: 3981

Answers (2)

William
William

Reputation: 4925

Just in case you have a space in a directory name you might want to use "$@", and it doesn't hurt to check that a directory exists:

  for dir in "$@" ; do
    if [ -d "$dir" ] ; then
      echo "Directory: $dir"
      ls "$dir"  # If all you want is to show the contents, this should do
    else
      echo "Not a directory: $dir"
    fi
  done

Upvotes: 2

Chris Montanaro
Chris Montanaro

Reputation: 18192

Something similar to this should work:

dirs=$*
for dir in $dirs
do
  echo "Directory: $dir"
  for filename in $(ls $dir)
  do
        echo $filename
  done
done

Upvotes: 0

Related Questions