Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Printing Directory Files

What's the best way to print all the files listed in a directory and the numer of files using a for loop? Is there a better of doing this?

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"

for file in "$target"/*
do
  printf "%s\n" "$file" | cut -d"/" -f8
done
like image 776
theGrayFox Avatar asked Mar 23 '23 02:03

theGrayFox


1 Answers

Here is a solution:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"
let count=0
for f in "$target"/*
do
    echo $(basename $f)
    let count=count+1
done
echo ""
echo "Count: $count"

Solution 2

If you don't want to deal with parsing the path to get just the file names, another solution is to cd into the directory in question, do your business, and cd back to where you were:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/$1"
pushd "$target" > /dev/null
let count=0
for f in *
do
    echo $f
    let count=count+1
done
popd
echo ""
echo "Count: $count"

The pushd and popd commands will switch to a directory, then return.

like image 82
Hai Vu Avatar answered Mar 31 '23 11:03

Hai Vu